如何检查它是否存在后,删除文件 [英] How to delete a file after checking whether it exists

查看:162
本文介绍了如何检查它是否存在后,删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在C#中删除一个文件,例如 C:\ test.txt的,虽然采用同一种方法,就像在批处理文件如:

 ,如果存在C:\ test.txt的

删除C:\ test.txt的

其他

返回任何结果(忽略)
 

解决方案

这是pretty的直观使用的文件类。

 如果(File.Exists(@C:\ test.txt的))
{
    File.Delete(@C:\ test.txt的);
}
 


由于克里斯指出,在评论中,你实际上并不需要做的 File.Exists 检查,因为 File.Delete 并不重要,如果该文件不存在,抛出一个异常,但如果你使用绝对路径,你将需要检查以确保整个文件路径是有效的。

How can I delete a file in C# e.g. C:\test.txt, although apply the same kind of method like in batch files e.g.

if exist "C:\test.txt"

delete "C:\test.txt"

else 

return nothing (ignore)

解决方案

This is pretty straightforward using the File class.

if(File.Exists(@"C:\test.txt"))
{
    File.Delete(@"C:\test.txt");
}


As Chris pointed out in the comments, you don't actually need to do the File.Exists check since File.Delete doesn't throw an exception if the file doesn't exist, although if you're using absolute paths you will need the check to make sure the entire file path is valid.

这篇关于如何检查它是否存在后,删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆