How to create a folder with c# which is NOT read only? - c#

In my C# forms application, I try to download the data in a directory of my SFTP Server. The data should be stored in a folder which I want to create in "MyDocuments". When the folder is created, I receive an Renci error "failure" because the folder is "read-only".
I tried many ways to create a folder, but I in most ways I used I either got an error, that I don't have the permission to create a folder, or I got an empty file instead of a folder. Right now I got a folder, but unluckily it is read only.
String localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\MyNewFolder\\";
if (Directory.Exists(localPath))
{
Console.WriteLine("Folder already exists");
}
if (!Directory.Exists(localPath))
{
Directory.CreateDirectory(localPath);
DirectoryInfo directory = new DirectoryInfo(localPath);
DirectorySecurity security = directory.GetAccessControl();
}
I expect the folder not to be read only, so that I can safe data in it using my programm. Anyone knows why my code still creates a read only one?

I believe you have to set the following using the DirectorySecurity object:
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\Account", FileSystemRights.FullControl, AccessControlType.Allow));
Then you can create the directory using the following:
DirectoryInfo di = Directory.CreateDirectory(#"directoryToCreatePath", securityRules);
EDITED:
Once you've created the directory using Directory.CreateDirectory(), you can then apply the following to the folder. This will allow the user you've specified to have FullControl of the folder. You can check the permissions for that user via Properties > Security
DirectoryInfo directory = new DirectoryInfo("C:\\CreatedFolder");
DirectorySecurity security = directory.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(#"USERNAME",
FileSystemRights.FullControl,
AccessControlType.Allow));
directory.SetAccessControl(security);

Related

Network path is not shared when trying to create folder with sharing everyone using c#

I have a wpf application in which i try to create folder on client machine and give sharing permission to everyone as i want to transfer crystal reports to those folders (unc network folder).I am able to create the folder with sharing permission showing as everyone with code but when i click the folder properties->sharing .It says network path not shared .
I have impersonated an administrator account and created the folder using below code ,i got from a stackoverflow post
private static void GrantAccess(string file)
{
bool exists = System.IO.Directory.Exists(file);
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(file);
Console.WriteLine("The Folder is created Sucessfully");
}
else
{
Console.WriteLine("The Folder already exists");
}
DirectoryInfo dInfo = new DirectoryInfo(file);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
}

UnauthorizedAccessException when using getAccessControl

I'm trying to copy files from external hard disk to folder in my desktop, in order to do that I have to take ownership of the folders and the files in the external hard disk, I read in previous questions about it how it has to be and my code looks like this:
using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
directoryInfo = new DirectoryInfo(path);
directorySecurity = directoryInfo.GetAccessControl();
directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
Directory.SetAccessControl(path, directorySecurity);
}
When I run this code I get an exception in the line:
directorySecurity = directoryInfo.GetAccessControl();
The exception is:
"unauthorizedAccessException was caught" "Attempted to perform an
unauthorized operation".
Why is that happen? And how can I copy these folders and files?

Move a folder on the same volume applying destination permissions

When copying a directory on the same volume (ex. c:) from one folder to another with the .NET DirectoryInfo.MoveTo, the access control are preserved: in other words the destination has the same security has the origin and does not inherit the one of it's new parent.
I would like to be able to move a folder and it's content but replacing the permissions like it was a copy of the folder.
Is there a simple way to achieve this in C#?
const string source = #"C:\test1\test";
const string target = #"C:\test2\test";
Directory.Move(source, target);
// Get Directory Info
var dInfo = new DirectoryInfo(target); // Or FileInfo
var dSec = dInfo.GetAccessControl();
// Set Security to inherit
dSec.SetAccessRuleProtection(false, false);
// Remove Rules/Accounts that are not inherited
var rules = dSec.GetAccessRules(true, false, typeof (NTAccount));
foreach (FileSystemAccessRule rule in rules)
dSec.RemoveAccessRule(rule);
// Commit changes to folder
dInfo.SetAccessControl(dSec);
At first move the folder. Then create a DirectoryInfo and get the AccessControl.
With SetAccessRuleProtection you can reset and inherit security from the parent.
Then remove all accounts/user that are not inherited.
The last line is to commit changes.
Files:
I the folder contains files and other folders, it depends on their security settings.
if they are set to inherit too then they inherit from the folder you changed with the code above (the parent folder)
so if you are not sure what they might be set to you have to do that recursive with all sub-folder and also with all files...
The Code for the Files is the same, except the DirectoryInfo there you have to use FileInfo.
For further information visit File.Move does not inherit permissions from target directory?
// Link for me, to read later: http://support.microsoft.com/kb/320246/de

windows forms app.config on common files folder

I have an application that stores single username and password on the app.config file.
I currently have the app.config writable on runtime so that the user will be able to change it.
problem begins upon installation using a setup project , the app.config is installed on the program files which is not writable for any user.
So , i have changed the app.config location upon installation to the common files folder so it will be accessible for reading and writing for all users.
Now, upon installation it seems that the data stored there is inaccessible at all , using ConfigurationManager.AppSettings["networkPath"] for example returns empty strings.
what am i doing wrong ?
You can do it in two ways:
Give special permission to app config file in program files by your installer. We do it using innosetup. If you are incapable of it, then do it from your program startup:
static void Main()
{
GrantAccess()
}
private static bool GrantAccess()
{
FileInfo fInfo = new FileInfo(Assembly.GetEntryAssembly().Location + ".config");
FileSecurity dSecurity = fInfo .GetAccessControl();
fSecurity.AddAccessRule(new FileSystemAccessRule("everyone",
FileSystemRights.FullControl,
AccessControlType.Allow));
fInfo .SetAccessControl(fSecurity);
return true;
}
Else you can choose another location to place your appconfig file, and then read it like this:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), Assembly.GetEntryAssembly().GetName().Name) + ".exe.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,
ConfigurationUserLevel.None);
return config.AppSettings.Settings["Key"].Value);
This is a poor choice in my opinion.

How can I deny a file from being copied?

I am working on an application that requires that some files are copied to a different folder. I use the following:
DirectoryInfo dir = new DirectoryInfo(path);
foreach (FileInfo filesindires in dir.GetFiles())
{
FileSecurity ds = filesindires.GetAccessControl();
ds.AddAccessRule(new FileSystemAccessRule("Authenticated Users",
FileSystemRights.FullControl, AccessControlType.Deny));
filesindires.SetAccessControl(ds);
}
With that method I deny the user from opening the file, but I would like to only prevent copying. How can I prevent that a file is copied while allowing the user to read it?
If you can read it, you can copy it.

Categories