C# 如何关闭另一个进程以释放文件锁?
我已经创建了一个按钮。在按钮的事件处理程序中,我要删除文件夹(abc)中的所有文件 以下是此操作的代码:C# 如何关闭另一个进程以释放文件锁?,c#,.net,windows,file,io,C#,.net,Windows,File,Io,我已经创建了一个按钮。在按钮的事件处理程序中,我要删除文件夹(abc)中的所有文件 以下是此操作的代码: private void button1_Click_1(object sender, EventArgs e) { MessageBox.Show("Are you sure!!!! The files in the folder will be deleted permanently"); this.Close(); str
private void button1_Click_1(object sender, EventArgs e)
{
MessageBox.Show("Are you sure!!!! The files in the folder will be deleted permanently");
this.Close();
string[] filePaths = Directory.GetFiles(@"C:\abc\");
foreach (string filePath in filePaths)
File.Delete(filePath);
}
例如,文件夹中有一个Word文件,如果打开该文件,我会收到一条错误消息:
进程无法访问文件“C:\abc\New Microsoft Word”
docx”,因为另一个进程正在使用它
您可以使用
Process
类查找该进程,强制关闭该程序,然后删除该文件。像这样的
Process [] proc Process.GetProcessesByName("winword");
proc[0].Kill();
但是我不建议这样做,因为windows也不会删除打开的文件。有一些示例可以找到持有锁的进程。@gp。这是原始线程:还有其他建议吗???谢谢@Nikhil…。它正在工作。。。