Find all files in a folder

后端 未结 3 1379
别那么骄傲
别那么骄傲 2020-12-01 10:12

I am looking to create a program that finds all files of a certain type on my desktop and places them into specific folders, for example, I would have all files with .txt in

3条回答
  •  爱一瞬间的悲伤
    2020-12-01 10:51

    First off; best practice would be to get the users Desktop folder with

    string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    

    Then you can find all the files with something like

    string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
    

    Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

    Then you could copy or move the files by enumerating the above collection like

    // For copying...
    foreach (string s in files)
    {
       File.Copy(s, "C:\newFolder\newFilename.txt");
    }
    
    // ... Or for moving
    foreach (string s in files)
    {
       File.Move(s, "C:\newFolder\newFilename.txt");
    }
    

    Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

    With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

    Check out these for more info:

    http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

    http://msdn.microsoft.com/en-us/library/ms143316.aspx

    http://msdn.microsoft.com/en-us/library/system.io.file.aspx

提交回复
热议问题