Delete files from directory if filename contains a certain word

前端 未结 5 1645
不知归路
不知归路 2020-12-30 00:15

I need to check a directory to see if there are any files whose file name contains a specific keyword and if there are, to delete them. Is this possible?

For exampl

5条回答
  •  我在风中等你
    2020-12-30 00:42

    You can use System.IO.Directory.GetFiles() to a list of the files, in string[] format.

    Then you can use System.IO.File.ReadAllText() to read complete files, or if they are very big, open a TextReader with System.IO.File.OpenText().

    If you are looking for a literal keyword, String.Contains() is all you need.

    Deleting a file can be done with System.IO.File.Delete(). Make sure the file is closed again.

    Edit, 2 examples of GetFiles():

    string[] fileNames = System.IO.Directory.GetFiles(@"C:\");
    string[] fileNames = System.IO.Directory.GetFiles(@"C:\", @"*.sys");
    

提交回复
热议问题