在C#.net中检查文件夹是否为只读

3
我正在使用asp.net(C#)4.0进行开发。在上传图片之前,我想要检查上传的文件夹是否存在。如果存在,我需要检查它是否为只读模式,如果是只读模式,我需要将其改为非只读模式。请问如何做到这一点?每次启动应用程序时,文件夹都被设置为只读模式,我希望通过编程来避免这个问题。
我的做法是...
            SaveFilePath = Server.MapPath("~\\_UploadFiles\\") + FileName;
            DirectoryInfo oDirectoryInfo = new DirectoryInfo(Server.MapPath("~\\_UploadFiles\\"));
            if(!oDirectoryInfo.Exists)
                  Directory.CreateDirectory(Server.MapPath("~\\_UploadFiles\\"));
            else
            {
                if (oDirectoryInfo.Attributes.HasFlag(FileAttributes.ReadOnly))
                {
                    oDirectoryInfo.Attributes = FileAttributes.Normal;
                }
            }

            if (File.Exists(SaveFilePath))
            {
                File.Delete(SaveFilePath);//Error is thrown from here
            }

这段代码在特定位置抛出错误。文件夹“_UploadFiles”只读,但仍未进入if语句以进行FileAttributes.Normal的操作。

错误信息如下: 拒绝访问路径'C:\Inetpub\wwwroot\WTExpenditurev01_VSS_UploadFiles\Winter.jpg'。


可能是从c#中删除文件夹的只读属性的重复问题。 - onof
1个回答

10

使用System.IO.DirectoryInfo类

var di = new DirectoryInfo(folderName);

if(di.Exists())
{
  if (di.Attributes.HasFlag(FileAttributes.ReadOnly))
  {
    //IsReadOnly...
  }
}

我该如何设置它为非只读状态?请查看我编辑后的问题,了解我到目前为止所做的事情... - Microsoft Developer
请在 Stack Overflow 上搜索,有很多类似的问题,尝试搜索 readonly directoryinfo,你会找到你需要的东西的;-) - Davide Piras
请查看我编辑过的问题。仍然出现错误。我已经提到了错误消息和我的代码。 - Microsoft Developer
@Chirag:将文件的“IsReadOnly”属性设置为“false”:System.IO.FileInfo file = new System.IO.FileInfo(SaveFilePath);file.IsReadOnly = false; - Tim Schmelter
2
应该使用 di.Exists 而不是 di.Exists() - MrJack Mcfreder
我一直在更改文件夹的只读属性,但是C#代码没有注册它。也就是说,带有“//IsReadOnly”的那个if块永远不会被执行。有人测试过吗?根据这个答案https://stackoverflow.com/questions/35337364/folder-directory-read-only,似乎对于文件夹来说这是不可能的。 - billy bud

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接