开发者

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?


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.


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.


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();
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜