简体   繁体   English

如何删除整个文件夹及其所有内容(包括只读文件)

[英]How to Delete a entire folder and all its contents including readonly files

i currently use this code to delete a folder and its contents: 我目前使用此代码删除文件夹及其内容:

string tempFolder = System.Environment.GetEnvironmentVariable("HomeDrive");
System.IO.Directory.Delete(tempFolder + "\\" + "Test", true);

and it works GREAT but, it will delete the folder and its contents but, will NOT delete read only files. 它可以很好地工作,但是会删除文件夹及其内容,但不会删除只读文件。 So how using c# targeted Framework of 2.0 can i accomplish this? 那么如何使用C#目标框架2.0来完成此任务?

You can remove the read-only attribute from the files using the following code: 您可以使用以下代码从文件中删除只读属性:

string[] allFileNames = System.IO.Directory.GetFiles(tempFolder, "*.*", System.IO.SearchOption.AllDirectories);
foreach (string filename in allFileNames) {
    FileAttributes attr = File.GetAttributes(filename);
    File.SetAttributes(filename, attr & ~FileAttributes.ReadOnly);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM