C# File.Delete 不删除文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2025482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File.Delete Not Deleting the File
提问by kevindaub
I am trying to delete a file, but the following code doesn't do that. It doesn't throw an exception, but the file is still there. Is that possible?
我正在尝试删除一个文件,但下面的代码没有这样做。它不会抛出异常,但文件仍然存在。那可能吗?
try
{
File.Delete(@"C:\File.txt");
}
catch(Exception e)
{
Console.WriteLine(e);
}
If the file can't be deleted, the exception should print out, but it doesn't. Should this fail silently (as in the File.Delete method is swallowing any errors)?
如果文件不能被删除,异常应该打印出来,但它没有。这是否应该无声地失败(如 File.Delete 方法正在吞下任何错误)?
采纳答案by Mitch Wheat
File.Delete
does not throw an exception if the specified file does not exist. [Some previous versions of the MSDN documentation incorrectly stated that it did].
File.Delete
如果指定的文件不存在,则不会抛出异常。[MSDN 文档的一些以前版本错误地说明它确实如此]。
try
{
string filename = @"C:\File.txt";
if (File.Exists(filename))
{
File.Delete(filename);
}
else
{
Debug.WriteLine("File does not exist.");
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
回答by BFree
Are you sure the file name is correct? The only time it doesn't throw an error is if the file doesn't exist. Stupid question, but do you by any chance have a typo in the file name? Or an error in the path?
你确定文件名正确吗?它不会抛出错误的唯一时间是文件不存在。愚蠢的问题,但你有没有机会在文件名中打错字?还是路径错误?
回答by Andy West
Check to see that the file's path is correct. An exception will not be thrown if the file does not exist. One common mistake is to confuse a file named File.txt
with one named File.txt.txt
if "Hide extensions for known file types" is set in Windows.
检查文件路径是否正确。如果文件不存在,则不会抛出异常。如果在 Windows 中设置了“隐藏已知文件类型的扩展名”,则一个常见的错误是将命名的文件File.txt
与命名的文件混淆File.txt.txt
。
回答by Elisabeth
Another possibility is that the file is still in use by some background process. Then it does not fail but it does not delete the file.
另一种可能性是该文件仍在被某些后台进程使用。然后它不会失败,但不会删除文件。
回答by David Galanti
Another example could be that the delete request is in a kind of queued state. For example when the file has been locked because it has not yet been closed after being edited by another process. If that is the case you can alter that process to close the file properly or kill the process and the file disappears.
另一个示例可能是删除请求处于某种排队状态。例如,当文件被另一个进程编辑后尚未关闭而被锁定时。如果是这种情况,您可以更改该进程以正确关闭文件或终止该进程并且文件消失。