【问题标题】:Create folder without read only attribute in C#在 C# 中创建没有只读属性的文件夹
【发布时间】:2014-01-30 13:28:15
【问题描述】:

我正在尝试在“c:\”文件夹(例如:c\)中从我的应用程序创建一个文件夹,但该文件夹始终是使用“只读”权限创建的。

我已经尝试了以下代码,但仍然无法更改属性。请帮帮我。,

方法一

var di = new DirectoryInfo(temppath);
File.SetAttributes(temppath, FileAttributes.Normal);
File.SetAttributes(temppath, FileAttributes.Archive); */

方法二

di.Attributes = di.Attributes | ~FileAttributes.ReadOnly;
File.SetAttributes(temppath, File.GetAttributes(temppath) & ~FileAttributes.ReadOnly);

方法三

foreach (string fileName in System.IO.Directory.GetFiles(temppath))
{
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);

    fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
    // or
    fileInfo.IsReadOnly = false;
}

所有这些方法都不起作用或只是更改文件而不是文件夹的属性。

【问题讨论】:

  • 关于方法 3:FileInfo 保存有关文件的信息。如果您修改 FileInfo 对象,则磁盘上不会发生任何事情。所以方法3不会对文件系统产生任何影响。 FileInfo 对象也需要 Refreh() 才能与文件系统同步。
  • 关于其他方法:Windows 上没有只读目录的概念。通过资源管理器设置该标志只会使目录中的所有文件成为只读文件,目录本身不支持它。见windows.microsoft.com/en-us/windows-vista/…

标签: c# file


【解决方案1】:

创建目录:

DirectoryInfo di = Directory.CreateDirectory(path);

来自 MSDN: http://msdn.microsoft.com/en-us/library/54a0at6s%28v=vs.110%29.aspx

如果您希望明确设置访问控制:

DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));

DirectoryInfo di = Directory.CreateDirectory(@"C:\destination\NewDirectory", securityRules);

【讨论】: