Directory.CreateDirectory access to path is denied?
Asked Answered
M

8

7

enter image description here

I have server-client application, it's a file manager
my problem is when I go inside a folder which requires access control like system folders, it becomes to read-only, but I need to move/delete or create new folder, how can I get the permission to do that?

here's how I create a new folder at the server side

public void NewFolder(string path)
    {
        try
        {
            string name = @"\New Folder";
            string current = name;
            int i = 0;
            while (Directory.Exists(path + current))
            {
                i++;
                current = String.Format("{0} {1}", name, i);
            }
            Directory.CreateDirectory(path + current);
            Explore(path); //this line is to refresh the items in the client side after creating the new folder
        }
        catch (Exception e)
        {
            sendInfo(e.Message, "error");
        }
    }
Maltz answered 25/2, 2012 at 13:8 Comment(2)
Are you (or the user running your application) able to navigate to the specified directory and create a new folder with standard operating system tools?Trant
now im using the application locally , server-client is the same computer.. i can't create new folder only when im in a system folder.Maltz
E
4

There are often directories on a drive that even a user with administrator privileges cannot access. A directory with a name like "HDDRecovery" is quite likely to be troublesome like this. Surely it contains sensitive data that helps the user recover from disk failure. Another directory that fits this category is "c:\system volume information", it contains restore point data.

An admin can change the permissions on folders like this. But of course that doesn't solve the real problem nor is it a wise thing to do. Your user can't and shouldn't. Be sure to write code that deals with permission problems like this, simply catch the IOExeption. Keep the user out of trouble by never showing a directory that has the Hidden or System attribute set. They are the "don't mess with me" attributes.

Extremely answered 25/2, 2012 at 14:42 Comment(4)
yea. you are right .. but in some cases i need to change or delete some files or folders in a directory like ProgramFiles .. sometimes uninstallers dont remove all files from its software so you need to delete them manually .. another reason that i have the same application but not a server-client .. its locally and i can modify the same folder.. and create a new directory ..Maltz
The user cannot mess with such files without UAC elevation. Which requires a manifest embedded in the executable to make Windows display the UAC prompt. Click the "Ask Question" button if you don't know how to do this and can't find another question about it as SO.Extremely
sir, I am getting the same error while creating the folders. So what exceptions I should check for ?? strReportDirectory = ConfigurationRead.GetAppSetting("ReportDirectory") + "\\"; strDateFolder = strReportDirectory + DateTime.Now.ToString("dd_MM_yyyy"); if (!Directory.Exists(strDateFolder)) { Directory.CreateDirectory(strDateFolder); } strFilePath = strDateFolder + "\\" + "Report.xlsx";Bellinzona
It is explicitly mentioned in the answer. IOException is a "it did not work" exception. There is nothing you can do about it yourself. You either have to stop trying or, more commonly, show the user the Message property so he can take corrective action. Letting your program bomb is also often quite acceptable if the error won't let your program do its job. Just make sure the user knows why.Extremely
C
5

I had a similar problem (asp.net MVC vs2017) with this code:

Directory.CreateDirectory("~/temp");

Here is my solution:

// Create path on your web server
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/temp"));
Chanticleer answered 24/7, 2018 at 12:3 Comment(0)
G
4

If you want to remove directory read-only attribute use this: http://social.msdn.microsoft.com/Forums/en/vblanguage/thread/cb75ea00-f9c1-41e5-ac8e-296c302827a4

If you want to access system folders you can run your program as local administrator.

Gouty answered 25/2, 2012 at 13:19 Comment(1)
im already running and debugging the application as an administrator .. still not working .. but i have exactly the same application but not server-client .. and it works.. that's what confuse meMaltz
E
4

There are often directories on a drive that even a user with administrator privileges cannot access. A directory with a name like "HDDRecovery" is quite likely to be troublesome like this. Surely it contains sensitive data that helps the user recover from disk failure. Another directory that fits this category is "c:\system volume information", it contains restore point data.

An admin can change the permissions on folders like this. But of course that doesn't solve the real problem nor is it a wise thing to do. Your user can't and shouldn't. Be sure to write code that deals with permission problems like this, simply catch the IOExeption. Keep the user out of trouble by never showing a directory that has the Hidden or System attribute set. They are the "don't mess with me" attributes.

Extremely answered 25/2, 2012 at 14:42 Comment(4)
yea. you are right .. but in some cases i need to change or delete some files or folders in a directory like ProgramFiles .. sometimes uninstallers dont remove all files from its software so you need to delete them manually .. another reason that i have the same application but not a server-client .. its locally and i can modify the same folder.. and create a new directory ..Maltz
The user cannot mess with such files without UAC elevation. Which requires a manifest embedded in the executable to make Windows display the UAC prompt. Click the "Ask Question" button if you don't know how to do this and can't find another question about it as SO.Extremely
sir, I am getting the same error while creating the folders. So what exceptions I should check for ?? strReportDirectory = ConfigurationRead.GetAppSetting("ReportDirectory") + "\\"; strDateFolder = strReportDirectory + DateTime.Now.ToString("dd_MM_yyyy"); if (!Directory.Exists(strDateFolder)) { Directory.CreateDirectory(strDateFolder); } strFilePath = strDateFolder + "\\" + "Report.xlsx";Bellinzona
It is explicitly mentioned in the answer. IOException is a "it did not work" exception. There is nothing you can do about it yourself. You either have to stop trying or, more commonly, show the user the Message property so he can take corrective action. Letting your program bomb is also often quite acceptable if the error won't let your program do its job. Just make sure the user knows why.Extremely
L
3

I also ran into an issue similar to this, but I was able to manually navigate through Windows Explorer and create directories.

However, my web app, running in VS on my laptop, hosted through my local IIS and not the built-in IIS deal for VS, was triggering the Access Denied issue.

So when I was hitting the error in code, I drilled down to glean more data from the System.Environment object and found the user, which of course was the App Pool that my app was running under in IIS.

So I opened IIS and opened the Advanced Settings for the app pool in question and changed the Identity to run under Network Service. Click OK. "cmd -> iisreset" for good measure. Try the app again, and SUCCESS!!!!

Largess answered 3/2, 2014 at 19:2 Comment(2)
Thank you so much! This was very helpful for me. I was looking through my code to figure out why this was happening. I forgot that IIS could be the problem!Pelagi
Thanks! This pointed me in the right direction, I had to specify the user in the IIS App PoolPippy
S
1

I had the same issue when creating a directory. I used DirectorySecurity as shown below:

DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(@"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(@"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));

DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);

Also keep in mind about the security as explained by Hans Passant's answer.

Full details can be found on MSDN.

So the complete code:

public void NewFolder(string path)
{
    try
    {
        string name = @"\New Folder";
        string current = name;
        int i = 0;
        while (Directory.Exists(path + current))
        {
            i++;
            current = String.Format("{0} {1}", name, i);
        }
        //Directory.CreateDirectory(path + current);
        DirectorySecurity securityRules = new DirectorySecurity();
        securityRules.AddAccessRule(new FileSystemAccessRule(@"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
        securityRules.AddAccessRule(new FileSystemAccessRule(@"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));

        DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);

        Explore(path); //this line is to refresh the items in the client side after creating the new folder
    }
    catch (Exception e)
    {
        sendInfo(e.Message, "error");
    }
}
Screamer answered 9/2, 2015 at 0:6 Comment(2)
You have the Identity hard coded. Would it not be best to grab the current user, or as Joe put it below the account trying to access the directory, dynamically?Bollay
If you want to give access to all users replace @"Domain\AdminAccount1" with "everyone"Hermann
N
0

My suspicion is that when you are running the application in client/server mode, the server portion needs to be running as Administrator, in addition to possibly removing read-only or system flags, to be able to do what you want.

That said, I agree with @HansPassant- it sounds like what you are trying to do is ill-advised.

Nazarius answered 25/2, 2012 at 15:54 Comment(1)
i agree with both of you .. but it's good to know about these stuff even if it's not recommended to do .. my application is not really for regular users.. its for administrators.. i would like to have a complete access and control in the other pcMaltz
L
0

Solved: Directory created on remote server using below code & setting.

Share folder and give the full permission rights also in Advance setting in the folder.

DirectoryInfo di = Directory.CreateDirectory(@"\\191.168.01.01\Test\Test1");

Test is destination folder where to create new Test1 folder(directory)

Lohse answered 15/3, 2017 at 6:37 Comment(0)
N
0

I had the same error (access is denied) in the following situation:

I had the following directory structure:

root/
├─ Nodes.xml/
├─ MyApp.exe

In this situation, I tried to create a file named Nodes.xml in the root directory, and this operation failed with an access denied exception, but what really was the problem is there was a directory with the same name.

After deleting the Nodes.xml directory, the issue was gone.

The exception information could be improved, for sure.

Non answered 15/3, 2023 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.