Riain McAtamney
Riain McAtamney

Reputation: 6432

C# Deleting files

In my codebehind I'm currently saving documents to a folder on the server. If the document is temporary I append "_temp" to the filename. On page load I want to check the server folder where these documents are held and I want to delete any of the temporary documents. i.e. the files that end with "_temp".

What would be the best way to do this?

Upvotes: 3

Views: 237

Answers (3)

Peter Kelly
Peter Kelly

Reputation: 14391

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

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

Or if you want to work with FileInfo (although it sounds like you don't but you never know...) rather than just the filenames you can create a DirectoryInfo object and then call GetFiles()

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

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

Upvotes: 0

Rippo
Rippo

Reputation: 22424

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 then you need to iterate through the results and delete them one by one. However this could be expensive for an asp.net site. Also you need to make sure that simultaneous requests does not throw exceptions!

I would recommend that temp files are stored in a single directory rather than put them in a dir that is shared with non temp files. Just for clarity and peace of mind.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500525

It sounds pretty expensive to do that on page load - I'd do it on a timer or something like that.

Anyway, you can use Directory.GetFiles to find filenames matching a particular pattern. Or if you'd rather not experiment with getting the pattern right, and there won't be many files anyway, you could just call the overload without the pattern and do the filtering yourself.

Upvotes: 4

Related Questions