如何在C#中删除文件和包含文件夹 [英] How to delete a file and containing folder in C#
问题描述
我在下面提到的路径中有一个文件。
\\10.242.29.232\Docs\DEV\417\59225e54-4892 -4ddc-8669-db47270645dd \rejection.doc
我的目的是删除名为'rejection.doc'的文件和'59225e54-4892-4ddc-文件夹' 8669-db47270645dd'。
提前致谢
我的尝试:
System.IO.File.Delete
I have a file in the below mentioned path.
\\10.242.29.232\Docs\DEV\417\59225e54-4892-4ddc-8669-db47270645dd\rejection.doc
My purpose is i want to delete file named 'rejection.doc' and folder '59225e54-4892-4ddc-8669-db47270645dd'.
Thanks in advance
What I have tried:
System.IO.File.Delete
推荐答案
FileInfo fi = new FileInfo(path);
DirectoryInfo di = fi.Directory;
if(di.Exists)
di.Delete(true);
您应该为此添加错误处理。 FileInfo和DirectoryInfo类都有一个应该检查的Exists()方法。
DirectoryInfo.Delete中的true(true)表示文件夹和内容应该被删除。
You should add error handing to this. Both FileInfo and DirectoryInfo classes have an "Exists()" method that should be checked.
The "true" in DirectoryInfo.Delete(true) says that the folder and contents should be deleted.
尝试Directory.Delete:
Try Directory.Delete:
string path = @"\\10.242.29.232\Docs\DEV\417\59225e54-4892-4ddc-8669-db47270645dd\rejection.doc";
string containingFolder = Path.GetDirectoryName(path);
Directory.Delete(containingFolder, true);
这篇关于如何在C#中删除文件和包含文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!