C# 删除一个 Directory/File 并设置 ReadOnly 属性

C# Delete a Directory/File and set ReadOnly Attribute

我有以下问题,我想删除 file/directory,但问题如下:我使用此代码

FileAttribute.ReadOnly 设置为 false
var di = new DirectoryInfo("FileToDelete");
di.Attributes &= ~FileAttributes.ReadOnly;

那我就这样做

File.Delete("FileToDelete")

然后抛出异常:

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

Additional information: The access to the path "FileToDelete" has been denied. //Changed the Path to FileToDelete

您必须 'apply' 使用以下属性:

File.SetAttributes(path, attributes);

你在做什么,你有一个表情 di.Attributes &= ~FileAttributes.ReadOnly; 代码中没有任何地方没有分配、使用等。 您还混合了 DirectoryInfo 和 FileAttributes。这是错误的。您真正想要的(根据描述)是将文件设置为只读,然后将其删除。 所以,你必须这样

File.SetAttributes("FileToDelete", File.GetAttributes("FileToDelete") & ~FileAttributes.ReadOnly);
File.Delete("FileToDelete");

另请注意,如果您没有足够的权限,您遇到的异常仍然会发生 https://msdn.microsoft.com/en-us/library/system.io.file.setattributes%28v=vs.110%29.aspx

至于目录

new DirectoryInfo("DirectoryToDelete").Attributes &= ~FileAttributes.ReadOnly;