Allow Created Directory to be Written To?

Hey!
So for my project I need to create a few folders that I can then use File.WriteAllText to add a text file in.
I created the folders fine using Directory.CreateDirectory, but when I try to write text to it, I get this error:

UnauthorizedAccessException: Access to the path ‘C:\Users\ygman\Desktop\NewFolder’ is denied.

Is there a way to add the proper permissions to a newly created folder?

As per a few other places I’ve looked, I tried this, but I’m still getting the error.

DirectoryInfo rootPathInfo = Directory.CreateDirectory(m_directorypath);
rootPathInfo.Attributes = FileAttributes.Normal;
File.SetAttributes(rootPathInfo.FullName, File.GetAttributes(rootPathInfo.FullName) & ~FileAttributes.ReadOnly);

Any ideas?

1 Like

Your best bet for a writeable directory is going to be Application.persistentDataPath. Try making a folder there.

Thanks for the reply!
I definitely see the advantages of that, but unfortunately, with my project I need the user to be able to choose where this/these folders are created.
I’m using an in-game file browser to select the location, then I create the folders there.

Then it’s pretty much outside of your application’s control. The user will have to make sure they pick a directory that is writeable by whatever user they ran the application as.

I believe typically the app runs as the user that started it though, so you might just have weird permissions settings on your Desktop or home directory. Check the windows permissions on those folders.

Strange, because I’m just testing by creating the folder on my desktop, which should have relatively open permissions.
Even if I do change my own permissions, there’s no guarantee that the end user will have the same situation, so that’s something I need to figure out, if that does end up working.

1 Like

Found the solution, for anyone else with this problem:
I was trying to write to the folder, not a file, which isn’t possible.
All I had to do is append the file name.

I changed the line from this:

File.WriteAllText(rootPathInfo.FullName, savedScene);

To this, and it worked:

File.WriteAllText(Path.Combine(rootPathInfo.FullName, fileName+extention), savedScene);
3 Likes