Getting Error : "file is being used by another process c#"
Getting Error : "file is being used by another process c#"
我正在尝试删除一个存在于我的硬盘上的文件,但出现无法删除该文件的异常,因为 'file is being used by another process'。
public void btnDelete(object sender, EventArgs e)
{
if(File.Exists("C:\\test.txt"))
{
File.Delete("C:\\test.txt");
}
}
确保文件不是由您自己或文件 reader 对象打开的。
尝试此逻辑以确保您打开以检查它是否存在的同一线程未保留对文件的引用,从而使您无法
public void btnDelete(object sender, EventArgs e)
{
var exists = false;
if(File.Exists("C:\\test.txt"))
{
exists = true;
}
if(exists)
{
File.Delete("C:\\test.txt");
}
}
您不能删除被其他进程锁定的文件。 OS 阻止了这种情况。无论如何,这里描述了一种方法:ForceDel - Delete locked files。从那里引用有关程序的信息:
Note: 1. SE_DEBUG privilege must be enabled.
2. The function works with every kind of HANDLE
3. It will bother the remote process :)
4. The handles will be invalid after you closed
them remotely
所以它甚至可以使其他进程崩溃。它的工作原理是
- 开启其他进程
- 在包含 of/executes CloseHandle()
的另一个进程中创建线程
- 等待线程完成
- 关闭线程和进程句柄
- 然后删除文件
您必须使用 P/Invoke interop
、here is some code demonstrating P/Invoke 将此 C 代码转换为 C#,但具有不同的功能。
我正在尝试删除一个存在于我的硬盘上的文件,但出现无法删除该文件的异常,因为 'file is being used by another process'。
public void btnDelete(object sender, EventArgs e)
{
if(File.Exists("C:\\test.txt"))
{
File.Delete("C:\\test.txt");
}
}
确保文件不是由您自己或文件 reader 对象打开的。
尝试此逻辑以确保您打开以检查它是否存在的同一线程未保留对文件的引用,从而使您无法
public void btnDelete(object sender, EventArgs e)
{
var exists = false;
if(File.Exists("C:\\test.txt"))
{
exists = true;
}
if(exists)
{
File.Delete("C:\\test.txt");
}
}
您不能删除被其他进程锁定的文件。 OS 阻止了这种情况。无论如何,这里描述了一种方法:ForceDel - Delete locked files。从那里引用有关程序的信息:
Note: 1. SE_DEBUG privilege must be enabled.
2. The function works with every kind of HANDLE
3. It will bother the remote process :)
4. The handles will be invalid after you closed
them remotely
所以它甚至可以使其他进程崩溃。它的工作原理是
- 开启其他进程
- 在包含 of/executes CloseHandle() 的另一个进程中创建线程
- 等待线程完成
- 关闭线程和进程句柄
- 然后删除文件
您必须使用 P/Invoke interop
、here is some code demonstrating P/Invoke 将此 C 代码转换为 C#,但具有不同的功能。