C # Deleting Files

In my code, I save documents in a folder on the server. If the document is temporary, I add "_temp" to the file name. When loading the page, I want to check the server folder where these documents are stored, and I want to delete any of the temporary documents. that is, files that end in "_temp".

What would be the best way to do this?

+3
source share
3 answers
string[] files = 
Directory.GetFiles
  (@"c:\myfolder\", "*_temp.txt", SearchOption.TopDirectoryOnly); 

or using linq

var files = from f in Directory.GetFiles((@"c:\MyData\SomeStuff")
    where f.Contains("_temp")
    select f;

Once you get all the files, you need to iterate the results and delete them one at a time. However, this can be expensive for an asp.net site. You also need to make sure that concurrent requests do not throw an exception!

, , , non temp. .

+4

- - .

Directory.GetFiles, , . , , .

+4
string[] myFiles = Directory.GetFiles(@"C:\path\files");

foreach (string f in myFiles)
{
    File.Delete(f);
}

FileInfo ( , , ...) , DirectoryInfo, GetFiles()

DirectoryInfo di = new DirectoryInfo(@"c:\path\directory");
FileInfo[] files = di.GetFiles("*_temp.txt");

 foreach (FileInfo f in files)
 {
     f.Delete();
 }
0

Source: https://habr.com/ru/post/1757625/


All Articles