3

I am working in asp.net(C#)4.0. Before uploading an image, I want to check that if the folder in which the image has been uploaded is exists or not. If it exists, is it read-only or not and if it is read-only, I want to make it not read-only. How can I do so. Each time when I start my application, the folder is set to read-only. So I want to avoid this problem by checking it all by programmatically.

I did like this...

            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
            }

This code throws an error from the specified place on code. The folder "_UploadFiles" is read only but still its not going in to the if statement to make FileAttributes.Normal

The error is.. Access to the path 'C:\Inetpub\wwwroot\WTExpenditurev01_VSS_UploadFiles\Winter.jpg' is denied.

Microsoft Developer
  • 5,229
  • 22
  • 93
  • 142
  • possible duplicate of [Remove readonly of Folder from c#](http://stackoverflow.com/questions/2316308/remove-readonly-of-folder-from-c) – onof Sep 22 '11 at 08:36

1 Answers1

10

use the System.IO.DirectoryInfo class:

var di = new DirectoryInfo(folderName);

if(di.Exists())
{
  if (di.Attributes.HasFlag(FileAttributes.ReadOnly))
  {
    //IsReadOnly...
  }
}
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • How can I set it to not read-only..? See my edited question for what I did till yet... – Microsoft Developer Sep 22 '11 at 08:27
  • please search here in SO, there are so many similar questions, try to search readonly directoryinfo and you will find what you need ;-) – Davide Piras Sep 22 '11 at 08:30
  • ..Please see the question that I have edited..Still getting an error.I have mentioned error message and my code.. – Microsoft Developer Sep 22 '11 at 08:44
  • @Chirag: set the `IsReadOnly` property of the file to `false`: `System.IO.FileInfo file = new System.IO.FileInfo(SaveFilePath); file.IsReadOnly = false;` – Tim Schmelter Sep 22 '11 at 08:53
  • 2
    It's `di.Exists` not `di.Exists()` – MrJack Mcfreder Aug 31 '18 at 17:01
  • I keep changing the folder's readonly property but the c# code doesn't register it. i.e. that if block with the `//IsReadOnly` wont ever be reached. Did anyone test this? It seems like it isn't possible for folders according to this answer https://stackoverflow.com/questions/35337364/folder-directory-read-only – billy bud Mar 23 '23 at 22:24