Working With The File System in C# - Managing Folders and Files

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
c-sharp can be a really powerful tool for working the file system it can automate file tasks including backup creation organizing files miring file info and more in this video where it gets started working with the files and directories now if you're new this channel my name is Tim Corrine it's my goal to make learning c-sharp easier there are a number ways to try to do that but the main was this YouTube channel I also run a training website where I have courses that will help you out if you come across a topic in c-sharp or related area like sequel or get did you'd like me to cover let me know and I'll add to my suggestion list most of my videos are directly based upon feedback from my viewers ok let's get started now I'm gonna start from a blank project today if you want the final source code there's a link in the description they'll take you to a blog post where you can download the source code for this video we're going to start with a console application so go file new project console application dotnet framework that's kind of important we don't want to deal with the.net core and this we want just the dotnet framework call us console UI and this is the file system demo ok the first time you only create a console application is we say console.readline at the end to stop it from going away and for this video we're in working mostly in the system dot IO namespace so we'll add that to our using statement right away now it shows in the console because it's really easy to work with and kind of just display we're doing really quickly instead of how to create lists and put them into you know bind them to something so let's start off with a path to our location of file system or a look at today the route path so let's call it route path equals let's say at sign and a couple double quotes now the app symbol what it does it allows me to use slashes without having it to escape them having to double them up so C colon slash and actually it's equal and slash not C colon slash and temp slash demos slash file system okay so that's that's the route path around work with that's where I've got some file setup let me just show you real quick I have root file one to which does W files and something in them and I've got subfolder a which has three files my file an a my second file and a and third file a and then I have subfolder B with different files and actually the the bitmap does have an image in it that's kind of drew something really quick so there's three files there so this is the the set up now on your machine if you want player less and try it out then you need to point it to the the correct path for your system so the first thing we're going to do is we're going to read all the directories in this path so let's do this let's say dir ask for directories no I'll abbreviate my thing for that's totally fine equals directory dot get directories we're not passing the path so route path and let's give us all the directories in this directory we could also have a search pattern and we can also specify search options like how far deep do you want we're going to go the whole DEP as an all sub full as well or not so we'll leave it as is for now and that returns oops not a string I want string array sorry so string array ders and now I can do is a for each now say string directory in directories now let's do a console.writeline to say what's the directory so if we run this there you go I have two directories subfolder a and subfolder B and it has the full path so e colon slash temp demos and we'll work on cutting that down and showing just the folder names in just a minute but for now the only one I show is don't have one let's create one sub sub folder C so now if I run this again so I got a sub folder inside of a but notice there's no sub subfolder C and that's because this is just at the root path that's it so just on that path itself no searching through directories below it so we can say a search pattern or we can say a search pattern and a search option so for search pattern we can just say star and the search options is all directory is not just top directories only so now if we run this notice it gets subfolder a and B but also inside subfolder a we have sub subfolder C so there we go now we've seen that we can get the the folders inside the folders and even if you wanted to the floors inside those folders so it kind of is recursive that way it's up to you if you want to do it or not this is a little dangerous if you point it at let's just say the C Drive means you have thousands of folders on your C Drive and so if you were say you know the path is just C colon slash just you know technically its backslash but I say slash because it's a shortcut a generic for a slash hopefully I mean by that but with this he keys at C colon and said give me all the folders underneath that that would take a lot and it would take some resources up and take some time as well like your application up for a while so let's not do that try and keep it as limited as possible to just the the ones you want in fact what you can do and this is something people often overlook is you can say you ignore the all directories change it back to just this directory which that's the default so you take it off it goes away and the way you do is when you loop through the directories you could determine if you want to then do a get directors on that directory or not that way you could say yes I want on C colon but I only want to dive deep if it doesn't say Program Files or Windows and then you get just your custom folders probably so that's an option as well but let's look at the next thing we can do with this and what he won the files instead of the directories and that's that's pretty simple so I can say I'm going to save our for this one of our files equals directory dot get files and we can have the root path and again we had that search pattern which let's just do startup star and the search options are all directories or top directory only let's start for the default of top directory only and do for each and it's actually a string file in files and we'll do console.writeline and just say the actual file itself so it's gonna loop through and find every file just in the top directory which as we know as Brent down here that would be root file 1 and root file 2 so if we run that there we go indeed we have those two files just root file one two and if we change this to all directories and then run again now we have two four six eight and it's in the different areas notice that it dives into those folders in fact if we put I go ahead and inside of subfolder a sub sub folder see let's create a new file and let's just make it a text file nested file one and now if we were us again we should have nine files including nested file one so it dives deep as you want into those sub folders you may say well that's great but those long names like as for this again those long names are ridiculous I don't want to know the whole path I just want to see root file one dot txt no problem let's comment this out and what we'll do instead it'll do the new console.writeline but this time whereas a path dot get file name and pass in the file now asks for a path right here and the reason it asks for a path is because it's asking for the full file name including the path so we pass in the file name which right now is the full file name I run this and now it's just the file names now if you did not want the extension on there there's another option let's actually is copy as you'd have you can see the different versions we do so I ctrl J here to pull a list and get file name without extension if you run that there's our file names no extensions and we can do it one more time and this time we can say get full path and run this it produces the whole file again with the file name attached so that's not necessarily as useful but just so you know if you if you wanted to ensure you had the full path or something essentially as prints the file back out the only time that's really a benefit is if you had a relative path when you passed it in so a relative path would be a dot slash my file XE then it would be a it expand that to e : / all we don't list the way actually wanted is get directory name there we go and that gives us the directory names of the files so there's where each of the files lives and of course that's not necessarily useful in a loop like we're doing here but if you had a full file with its path you could grab just extension just a file name the file name with the extension or just the path then kind of break those things apart and use those for different reasons now what if you want some information about a file so you've got this file but you I know me how big it is well you can do that here so console.writeline and actually I do either might have a line above this this was a var for now because it's a little easier to start off this way and say info equals new file info about he pass in the file name so file and now we can say info dot and a whole bunch of information in here but one of them is length if you know this is the size in bytes of the current file so let's actually just so we have a little more information little context around it let's do our dollar sign syntax which is that string interpolation and we're gonna say path dot git file name with the out extent well get filename is fine I'll see the extension on and whereas say info dot length and bytes after it's and get filename we kind of pass in the file there we go so now I should get the file size for each of our files in fact most of them are empty but we have the the B folder to dot Excel file actually has some size to it and the bitmap has a lot more size to it maze and bytes which if you want to convert that to kilobytes or megabytes that would be yours to create you you work on that it's basically just dividing by a thousand 24 take kilobytes and again for megabytes and again for petabytes so that's the file info is a lot more info can get here if you look at info you have the last right time you have the last access time you have the create information create time and you have some attributes as well that be things like does it have the archive flag a lot of flags like that you probably need those for most things but if you find out this read-only or not and a bunch of information like that you can even open it if you want to now just so you're aware that gets a little tricky when you have files that candice Lee open inside c-sharp directly Excel files kind of problem if you just try to open them and modify them so that gives us all the information about the files and folders on our filesystem but that's just kind of a read access version of our file system let's talk about how we can kind of use these things or to advantage them and so one of the ways we can do things is we can create automation tasks with c-sharp and one of the easiest things that do in automation with c-sharp is file system manipulation so for example if you always do a certain thing with files well you can use c-sharp do instead or if you want a tool that kind of repeats things over and over again you can do that as well or verify certain things are in place or like same things set up so for example if you deploy your application to a system and you'll make sure that it has a temp folder and that it has a log file in that temp folder that's already set up and you just blank and ready ready to go those kind of things that's what this is great at so let's look at a couple of tasks you might do with c-sharp and the first one is let's verify if a directory exists so directory dot exists that's really simple right director Dai exists and we'll see whether or not this path exists on disk so I'm gonna say dollar sign a couple double quotes oops in that dollar sign I want the @ symbol whereas a e colon slash temp slash demos slash file system that's our kind of root of our or a plane around and then in here I'm gonna say sub folder C which does not exist so if you look here I have subfolder a and B inside a is sub sub folder C we don't have a sub fuller C so and this returns a boolean so we can say you know just console.writeline and say well actually it's an if statement makes it easier for the console.writeline if directory exists I'm gonna leave it just like that directory exists this is the implicit way of doing things and because it's named nicely then directory exists makes it easy to read this if directory exists do this if directory does not exist do the other thing so that's case the directory exists else the directory does not exist and we hit start and we see the directory does not exist now if I change this to subfolder a now I'm gonna do lowercase here just kind of prove a point the directory exists now if we look sub fuller a the a is capitalized that's because we're case insensitive at this point we don't really care about case let's drink I just see from it so what if this directory does not exist well what if we said directory dot create directory and it says creates all directories and subdirectories in a specified path unless they already exist this is an awesome little tool let me hit the path so let's let's put this into a variable first so I'm going to grab this whole thing right here I'm gonna control X out and we're gonna say string new path equals and that path now just a little more complicated we're gonna say sub sub-folder d so is actually two layers here that don't exist it's right check to see if that path exists if it does not exist where I create that directory and then we'll look at it in the folder and we'll run it again just kind of verify so it says the directory does not exist but now if we look subfolder C does exist and sub-sub full or D exists as well so create both of those subfolders now if I run this again it should just say that the directory exists but even cooler is what I don't care I'm just gonna copy this and I'm gonna say I don't really care if the subfolder exists or not go ahead and create it and in fact I'm gonna put something in subfolder C I'll put a file yeah new text about documents fine and then something else in let's put a an Access database there you go so it's an Access database in subfolder or sub sub full or D now let's Russ again where I'm just gonna create it I don't really care if it's there or not I hit start and of course just empty screen I hit enter it's clothes because I didn't planning to the console but now if I come here to subfolder see that foul still exists a subfolder D that file still exists it didn't crush anything it just created if it exists it or if it did not exist so that means we don't need to check first if you just run this it's a go ahead and create the directory for you now it takes a little bit of work but so does checking a see if a directory exists so really if you're gonna think about crane directors or the directory might not be there this right here is really handy just go ahead and power through and create the entire path now let's talk about files so let's copy or come in this out let's talk about first of all copying files so we have two folders in the root we have root file one and root file - what if you want to copy these files and put them into subfolder a which are not there right now so let's do that I'm going to say string array oops let me just built right string array files equals and we'll say directory dot get files and where I pass in the root path but I'm not gonna pass in a filter I'm not gonna pass in a get the sub files as well just get the files in the root path I'm gonna say for each I'll say string file in files so for each of these files which there should be let me - and just to verify that there are so we don't mess anything up let's run this I did a console.writeline and sure enough there's just those two files let's go ahead and grab the root file and copy this real quick and come down here and paste it and we'll say this is the destination folder and we'll call will say that the destination folder is sub folder a we should know exists so I won't do it to check for it but if you're actually like make sure that you're moving things or copying things I'd verify that this exists so for each file and file instead of do a console.writeline what we're going to do is we're going to say file dot copy and the source file is file and the destination file is going to be the destination folder now here's where actually it's string interpolation so I'll say dollar sign couple of double quotes I'll pass in first the destination folder and they'll pass in the slash character which I felt I'll pass that in at the end right here and now I'll pass in path odd get file name with extension so need to say without extension and the file so right now I've done is I said here's the desk here's the the source file which is that root file one or roof l2 and then here's the destinations gonna go to including the file name so there's the destination folder which is this right here and then I said give me just the file name this is where that really comes in handy so we're not renaming a file and it has the right extension as well now there is another option if you hit comma and that's do you want to allow over rights so an overwrite is if the file exists we want to take this new file and it put it in place of that existing file so we'll say true so let's start this and of course nothing what happens there's no output to the screen we hit enter let's go here to subfolder a and now we have root file one and root file - so they're both of there now let's just demonstrate what would happen if I didn't name these this way so instead of getting the file name I am going to do Smee a bit different and comment this out real quick and sent me into a for a for loop so for I equals 0 I is less than files dot length and I plus plus well this allowed me to do is have an index that I can work with so he grass aim thing and copy it and paste it but this time instead of file dot file name dot or a get file name I'm gonna say I dot txt so it's gonna have a number of the file we're copying and dot txt and this is going to be files and it's gonna be I like so and now if we run this it's it's run trust me because subfolder a and now we have zero and one txt there's those two files so we can rename as we go so for example if you're copying from one location to another but you want to in the process change the structure or give it a more easily identified number or whatever you want to do that's no problem you can just read it in your system and change it as you go now it's kind of proved let's just open this up and say hello world save this and that's in the subfolder a where it says hello world let's rise again and it's done so now subfolder a zero is empty again because it over wrote now if I change it again hello y'all and it is there now we can do is down here we can say false for don't overwrite and it says hey there's already a file that exists here and step throws an exception so that's either the process that are handled yourself maybe I ignore it that's fine wrap it a try catch and say if it is a system that I owed I owe exception then we can ignore that error and continue on but this way it safely prevents us from doing something we didn't want which is overwriting this file now let's comment this out and what if you wanted to do instead of a copy you want to do a move copy this and paste it down below it'll uncomment it and instead of file copy we'll say file dot move now there's no option for whether you want an overwrite or not so file that move doesn't have the Dumont will allow overwrites so let's see what happens when those files already exist so remember that the root file one two or we're copying over or moving over now let's see what happens when we run this it says no you can't read it because they already exist so let's do this just kind of demonstrate it does work for moving I'll delete the two and we're out run again and it runs and now root file ones who are there but they're not at the root so that's how we can move things around if we want to undo scale so that's why that's the start of what you can do the filesystem but I want you to think through all the different possibilities of how you can work with a file system to really automate some of your daily tasks this is one of those areas where if you want to create an application to kind of show off your c-sharp skills it's a great way a great starter type thing because you can start really small and start growing up over time with what your automation system does for instance I'll show you a demo here just kind of show off what you could do if your filesystem accumulates temp files or other type files that are kind of clogging up and there's there's tools out there you can you can buy or you can get for free that will go through and clean up different temp folder and those kind of things but maybe instead of using a a tool that has a lot of overhead and does other things and tries to get you to buy it and all the rest what if you create your own tool and that's where let's grab the the for each here now copy and paste this and uncomment the whole thing I actually need to grab this line as well or I'll grab all directories in our root directory that's all directories and if we just start with the basics so just the the file names let's grab the the full path let's comment out these as well so you run this that's the all our files in there sub their folders in our root folder but what if we did this what if we say you know what instead of startup star I only want the xlsx files the excel files let's run that and there's just one file so we can kind of narrow in our search and say no you know what I only want I want any file type we want but I want something that says folder they run that and there's three files that have folder in their name so you can kind of dial in on just the the files you want and then you have a routine that goes through and deletes those files or one that moves them into an archive folder so if may it's a log file and one cause it kind of important sometimes but made it go to your C Drive and your C Drive doesn't have a lot of space but you have a external hard drive where you have a second hard drive in a computer you could have a routine that goes through and moves the files from your C Drive over to a log directory on your secondary hard drive and that would clean it up or maybe you're working in Visual Studio which surprised but you want to be able to take your files and move them or copy them to a thumb drive so you can take them somewhere else well you can create an application that just says here's the route of my project folder so they have all my projects I possibly created and grabs them all and it copies them over to your thumb drive and maybe even it says you know don't copy of our exists or May it says you don't overwrite it and just get all the make sure you have the latest version and they have the same thing in Reverse you're coming back you get your thumb drive you've made some changes you hit the other direction and it overwrites the other way and now you have all your latest changes on your computer and you still have that backup on your thumb drives you have kind of the both options there now as we need some future videos that going into even more things you can do and give Kass some more tools to work with the file system and things you can do with a file system so my encouragement to you is a star up by using this and try and create couple ideas in your mind of ways you can make your life a little easier whether it's managing your files on your desktop or whether it is backing up files to a thumb drive or managing cleaning out the those extra files to be created whatever it is get some demos out there and kind of start working with this and then as we go through other videos you can kind of expand your knowledge and expand what you can do with c-sharp because the more you use it the better off you'll be with it all right so that's my video for today I hope you enjoyed it definitely the comments down below as to your thoughts once you've used it for I'd love to hear your ideas and how you made use of this in order to really make C sharp work for you okay thanks and as always I am Tim quarry you [Music]
Info
Channel: IAmTimCorey
Views: 87,872
Rating: 4.9503722 out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, file system, c drive, c# file system, c# file selector, copy file, c# copy file, c# move file, c# system.io, System.IO, managing file folders, managing folders, managing files, c# backup
Id: 9mUuJIKq40M
Channel Id: undefined
Length: 35min 6sec (2106 seconds)
Published: Mon Nov 26 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.