c#--a simple File Manager

Source: Internet
Author: User
Tags try catch

Recently in the tense of learning C #, to tell the truth about C # before there is not much contact, only know that C # features and Java very similar, after contact only to find that C # compared to Java is not a lot of differences, but it is a realization of the program ability is better than Java language (representing personal views only).

There are many beginners in the Learning programming language, will be stuck on the recursion, understanding and application will be very difficult, so I myself try to write a very simple and simple file management program, said it is simple because he really no difficulty, are very low-level loops and recursion, There are only more than 130 lines of code, just hope to help you understand the application recursion. If you have a bit of programming base wood there, then please do not directly to try recursion and various loops, please step by step solid to learn from the beginning.

This is very simple, simple, simple. The file management program provides several functions: retrieving the total number of files under the user input path, retrieving the number of folders under the user input path, and retrieving the number of files in the user input path that match the input characters at all ends. This may be a bit abstract, first put a picture of the results of the program run.

I used this applet to retrieve the total number of files in the Autodesk folder under my C drive, the total number of folders and the total number of TXT files, and finally quit the program. Then I came to the Autodesk folder, right-click Properties, and confirmed that the number is indeed correct. And as for the number of TXT, I in the folder window Search bar input txt, a total of 182 results, but I counted one by one, 6 is the beginning of the TXT, so 176 is accurate. If you want to have our code function programmed to contain the three characters of TXT instead of the three characters, simply modify them later, and don't repeat them here.

All right, gossip's not much, just stick to the code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.IO;//need to introduceusingSystem.Threading;//need to introduceNamespace Filesmanager{class Program {//filesnumber Method        #  Region        Static intFilesnumber (stringPath) {intCount =0;Try{varFiles = directory.getfiles (path); Count = files. Length;vardirectories = directory.getdirectories (path);foreach(varDirecinchDirectories) {count + = Filesnumber (Direc); }            }Catch(UnauthorizedAccessException exception) {Console.WriteLine (Exception).            Message); }returnCount }#endregion         //directoriesnumber Method        #  Region        Static intDirectoriesnumber (stringPath) {intCount =0;Try{vardirectories = directory.getdirectories (path); Count = directories. Length;foreach(varDirecinchDirectories) {count + = Directoriesnumber (Direc); }            }Catch(UnauthorizedAccessException exception) {Console.WriteLine (Exception).            Message); }returnCount }#endregion         //findextension Method        #  Region        Static intFindExtension (stringPathstringextension) {intCount =0;Try{varFiles = directory.getfiles (path);foreach(varFileinchfiles) {if(file. ToLower ().                EndsWith (extension)) count++; }vardirectories = directory.getdirectories (path);foreach(varDirecinchDirectories) {count + = FindExtension (direc, extension); }            }Catch(UnauthorizedAccessException exception) {Console.WriteLine (Exception).            Message); }returnCount }#endregion         //main Method        #  Region        Static voidMain (string[] args) {stringpath, extension, order; Thread.Sleep ( -); Console.WriteLine ("program started, designed by Mr.losers"); Thread.Sleep ( -); Console.WriteLine ("Special thanks to: Ho shopkeeper's"); Thread.Sleep ( -);            Console.WriteLine (); Console.Write ("To calculate the number of files under the path, enter the number of file clips in the 0\n calculation path, enter 1\n"); Console.Write ("Search path under File name match number Please enter 2\n exit program Please enter q\n"); Do{order = Console.ReadLine ();if(Order = ="0") {Console.Write ("The file management system is ready!\n Please enter the path you are looking for: \ n");                    Path = Console.ReadLine (); Console.WriteLine ("The total number of files under this path is: {0}", Filesnumber (path));                Order = Console.ReadLine (); }if(Order = ="1") {Console.Write ("The file management system is ready!\n Please enter the path you are looking for: \ n");                    Path = Console.ReadLine (); Console.WriteLine ("The total number of folders under this path is: {0}", Directoriesnumber (path));                Order = Console.ReadLine (); }if(Order = ="2") {Console.Write ("The file management system is ready!\n Please enter the path you are looking for: \ n");                    Path = Console.ReadLine (); Console.WriteLine ("Please enter the name of the file you want to match:");                    Extension = Console.ReadLine (); Console.WriteLine ("The total number of files that match the name is: {0}", findextension (path, extension));                Order = Console.ReadLine (); }if(Order = ="Q") Break;Else{Console.WriteLine ("Input Error Please re-enter:"); }            } while(true); Console.Write ("Thanks for using!"); Thread.Sleep ( -); }#endregion }}

After you post the code, simply explain what's included in it.

The first thing to say is a few points:
The first is that I used multiple Var,var in code, which is a handy use in C # that allows the compiler to determine the type automatically. such as the directory.getfiles here (path);
Returns an array of type string, which is an array of paths that contain each file under path paths. var files = Directory.GetFiles () is equivalent to string [] files = directory.getfiles (path)

The second is the preprocessing directive, which #region和 #endregion, facilitates the management of the Code, and the code in one area.

The third is a try catch statement, in this program we each file search method used the statement, because whether it is C or D disk and other disk characters will have files we do not have access to, so we want to catch unauthorizedaccessexception, and print out this exception information so that we can know that the files are not accessed further, and that the program is not interrupted because of exception.

The fourth is that we need to introduce two namespaces at the beginning, because the method we use Thread.Sleep () needs to introduce system.threading; GetFiles () and getdirectories () need to introduce System.IO;

Here we look at the code in order, first of all, the Filesnumber method, three methods have used the idea of recursion, this method needs to pass in a parameter path, both the search path. Count is the counter that calculates the number of files.

First, we count all the files in the path that we passed in, so count = files. Length, and then take out all of the directory in the path, which is the folder where you can continue to explore, followed by a very important step-recursion, to continue this method for the directory removed from each path. The new count value is added to the current count and the layer is down until there are no folders to continue exploring.

Calling yourself in a method is the basic idea of recursion. We assume that there are 10 files under Path, 3 of which are path1,path2,path3, and that the code is actually executed as follows: Count (path) = number of files under Path paths +count (path1) +country (path2) + Count (Path3), and then there are files and folders inside the Path1,path2,path3, so the decomposition continues.

Give a mathematical example to help you understand:
128 = 64 + 64 = 64 + (32 +32) = 64 + ((16+16) + (16+16)) = 64 + (((8+8) + (8+8)) + ((8+8) + (8+8)), although not exactly the same,
But the truth is similar, is a layer of decomposition process. I have used life to explain, still do not know how to think more, or to seek another job to ...

After explaining the filesnumber words, Directoriesnumnber is more simple than filesnumber to use the same recursive method, which is skipped.

FindExtension method Just make a little change, first method passed two parameters, a path, a matching extension extension, here note I use two methods, ToLower method ensures that the case of matching files can be found, EndsWith () is back-end matching, of course, we can also use Startwith () and contains (), if you search for a small number of files, and we can also find the file, enter its current path, these to the reader to modify it, in fact, it is relatively simple, In order to ensure that the program is concise there is no output path, more than 100 paths out of the output is also very painful.

Next come to the main method, note that the main method in Java is lowercase main, and in C # you need to capitalize.

The first half of the main method is to define and output the usage method. Because I have a slight obsessive-compulsive disorder, I think that adding a delay to the output will make people feel more comfortable and will look at the words appearing on the screen carefully. So I joined the sleep method, and I started by setting the Sleep2000 milliseconds you believe ....

The Do and loop after the output text is the main body of the program. In fact, you can use the while, but do not know why I write, with a do while, you will find me back while the condition is true, that is, he will continue to execute, until the user input Q break out .....

This loop will first ask you to enter, according to the user will know the input 0, 1, 2, q to select the function, and then the program will be based on the user input different characters to hold the function is not feasible to call different methods, after execution immediately reset, to prepare for the next use. Because the input is a string, I do not convert to the int type and then use the switch statement.

Actually now take a closer look at this program is really simple very simple very simple, the simplest recursive, the simplest loop, so we have to marvel at the code is really amazing things, I still remember the first two days to give this small thing to the female votes do not understand the programmer to see when she unexpectedly thought this small program is very powerful, can sell, is also a show tease.

Finally, I hope to help everyone, C # is really a very good language.

Another: If you have found some errors or better improvements also please advise, please email, private messages or Weibo contact me.

2015.4.5 15:39
by Mr.losers

c#--a simple File Manager

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.