【发布时间】:2012-05-17 07:01:48
【问题描述】:
我创建了一个简单的程序来删除 C# 中的临时文件(为了好玩,不是主要项目)并且遇到了锁定文件(正在使用)的问题。您通常如何排除这些文件?作为参考,我收到了错误:
该进程无法访问文件“ExchangePerflog_8484fa31c65c7a31cfcccd43.dat”,因为它正被另一个进程使用。
代码:
static void Main(string[] args)
{
string folderPath = string.Empty;
folderPath = System.Environment.GetEnvironmentVariable("temp");
deleteFilesInDirectory(folderPath);
}
public static void deleteFilesInDirectory(string folderPath)
{
try
{
var dir = new DirectoryInfo(folderPath);
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
dir.Delete(true);
MessageBox.Show(folderPath + " has been cleaned.");
}
catch (System.IO.IOException ex)
{
MessageBox.Show(ex.Message);
return;
}
}
【问题讨论】:
-
澄清一下,您是要跳过正在使用的文件,还是要强制删除它们?
-
为什么不只收集未删除的文件并在执行后显示它们?或者您需要等待它们访问?
-
他说排除所以我认为他的意思是跳过
-
这个问题已经回答了,检查一下:stackoverflow.com/questions/6077869/…
-
还有一个名为“Unlocker”的实用程序 - emptyloop.com/unlocker 这可以释放锁(以及告诉你谁拥有它们)然后允许你删除它们。不过,更多的是用于调查而不是一般用途。
标签: c#