I am creating a new folder in documents and after that I want to write a file to it. The problem is, is that the folder I create is 'read only'. So I can't add a file to it. I can't fix it.
What I have now:
string target_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "data");
Directory.CreateDirectory(target_path);
var di = new DirectoryInfo(target_path);
di.Attributes &= ~FileAttributes.ReadOnly;
I also made my program startup as administrator but that doesn't make any difference.
Edit
When trying to store a file inside the folder I get the following error:
System.UnauthorizedAccessException: 'Access to the path "xxxx"' is denied.'
try explicitly set permissions.
string target_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "data");
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule("Users",FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(target_path, securityRules);
Related
DirectoryInfo di = new DirectoryInfo(#"c:\windows\temp");
Here I want to replace c:\ with the current drive on which the user is operating windows.
Is it possible to do that?
In .net you ought to use Path.GetTempPath to get a temporary path:
https://learn.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath?view=net-7.0&tabs=windows
Both Environment.GetEnvironmentVariable("SystemRoot") and Environment.GetEnvironmentVariable("windir") should give you the path in form of "driveLetter:\\Windows"
So you can do:
DirectoryInfo di = new DirectoryInfo(Environment.GetEnvironmentVariable("SystemRoot"));
For the difference between "SystemRoot" and "windir" see:
https://superuser.com/questions/638321/what-is-difference-between-windir-and-systemroot
DirectoryInfo di2 = new DirectoryInfo(Environment.GetEnvironmentVariable("SystemRoot"));
string path = Convert.ToString(di2);
DirectoryInfo di = new DirectoryInfo( path + #"\temp");
I figured it out. Here is the corrected code.
I am trying to change ownership of a windows folder and everything inside it. Basially I am trying to check the box that would be there if you did this manually in windows that says "Replace owner on subcontainers and objects". This will need to work over a network share path. I am able to get 1 folder deep but then it just stops there. This does not include the base folder changing either.
foreach (string directory in Directory.GetDirectories(dirPath))
{
var di = new DirectoryInfo(directory);
IdentityReference user = new NTAccount(Login.authUserName.ToString());
DirectorySecurity dSecurity = di.GetAccessControl();
dSecurity.SetOwner(user);
di.SetAccessControl(dSecurity);
}
You can use Directory.GetDirectories with SearchOption.AllDirectories in order to recurse.
But it seems easier to just get the DirectoryInfo di objects directly using DirectoryInfo.GetDirectories, which has the same and more recursive options.
IdentityReference user = new NTAccount(Login.authUserName.ToString());
var root = new DirectoryInfo(dirPath);
foreach (var di in root.GetDirectories("*", SearchOption.TopDirectoryOnly).Prepend(root))
{
var dSecurity = di.GetAccessControl();
dSecurity.SetOwner(user);
di.SetAccessControl(dSecurity);
}
I want modify the file's permission, and I am talking about permission like 666 / 777 etc.
In other words how tio change the permission of file from ANY to 666.
The goal is changing the permission of uploaded file on my ASP.NET MVC Web App.
public string Uploadfile(HttpRequestBase currentRequest)
{
string fileName = "";
for (int i = 0; i < currentRequest.Files.Count; i++)
{
if (currentRequest.Files[i].ContentLength > 0)
{
string strFileName = Guid.NewGuid().ToString() +
Path.GetExtension(currentRequest.Files[i].FileName);
currentRequest.Files[i].SaveAs(HttpContext.Current.Server.MapPath("/Upload/Task/" + strFileName));
fileName = strFileName;
}
}
return fileName;
}
}
You should look at File.SetAccessControl Method
public static void SetAccessControl(
string path,
FileSecurity fileSecurity
)
For example this is how you get the FileSecurity's of a file
FileSecurity fSecurity = File.GetAccessControl(filePath);
Then you create a FileSystemAccessRule
FileSystemAccessRule rule = new FileSystemAccessRule(SPECIFIC_USER, FileSystemRights.FullControl, AccessControlType.Allow);
And you add this Rule to the file's FileSecurity
File.SetAccessControl(filePath, fSecurity);
List of FileSystemRights possible values
http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemrights(v=vs.110).aspx
Windows file security works differently to Unix, and there is no direct equivalent to chmod 666.
The method you're looking for is File.SetAccessControl, which takes the path to the file, and a FileSecurity object. The closest equivalent to '666' is probably to assign read/write permissions to the 'Everyone' user account.
To do this, you would use File.GetAccessControl to retrieve the current permissions for the file, add in the new read/write permissions to the FileSecurity object you just retrieved, and then use SetAccessControl to write the new permissions.
More information is available on MSDN here: http://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol%28v=vs.110%29.aspx
How can I set the initial directory to be where my test data exists?
var relPath = System.IO.Path.Combine( Application.StartupPath, "../../" )
dlg.Title = "Open a Credit Card List";
dlg.InitialDirectory = relPath ;
The default directory it opens up to is where the .exe exists: Project2\Project2\bin\Debug
I want it to open up by default in the Project2 folder where my test data exists. But it does not allow me to move up a parent directory. How do I get around this?
You can use Directory.GetParent(string path)
string relPath = Directory.GetParent(Application.StartupPath).Parent.FullName;
Or using DirectoryInfo
DirectoryInfo drinfo =new DirectoryInfo(path);
DirectoryInfo twoLevelsUp =drinfo.Parent.Parent;
dlg.InitialDirectory = twoLevelsUp.FullName;;
To convert your relative path to an absolute path you can use Path.GetFullPath()
var relPath = System.IO.Path.Combine(Application.StartupPath, #"\..\..");
relPath = Path.GetFullPath(relPath);
dlg.InitialDirectory = relPath;
Alternatively if you wish to change the working directory to your test data:
Directory.SetCurrentDirectory(relPath);
More information:
http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx
I am Trying to write a Functionality where i could get the Complete List of All File Name in all Drives,but I am stuck in a place where its giving me security exception to read all files.
I went through many of the articles in this site and the other, but unable to figure out how to set complete access rights
this post was much useful but i am getting an Exception which was unanswered in that thread
How to grant read access to all files in a folder and subfolders using c#?
Now My code looks like this
[FileIOPermission(SecurityAction.LinkDemand, Read = "C:\\")]
public void GetAllFilesFromPhysicalDrives()
{
List<DriveInfo> allphydrives = GetListofPhysicalDrivesOnly(); //Gets All Physical DrivesCollection
try
{
foreach (DriveInfo dr in allphydrives)
{
DirectoryInfo dir = new DirectoryInfo(dr.Name);
DirectorySecurity dirSecurity = dir.GetAccessControl();
dirSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Read, AccessControlType.Allow));
dir.SetAccessControl(dirSecurity);
FileSystemAccessRule faRule;
FileSystemRights fsrRights;
DirectorySecurity dirsec;
fsrRights = FileSystemRights.FullControl;
faRule = new FileSystemAccessRule(new System.Security.Principal.NTAccount("my-pc\\me"),fsrRights,InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly, AccessControlType.Allow);
System.Security.Principal.NTAccount account = new System.Security.Principal.NTAccount("me\\me");
dirsec = Directory.GetAccessControl("C:\\");
dirsec.SetOwner(account);
dirsec.AddAccessRule(faRule);
Directory.SetAccessControl("C:\\", dirsec);
}
}
catch(Exception ex)
{
}
}
so when the code to set the access executes i am getting an "Attempt to Perform UnAuthorized Operation" Exception
I don't want to set Permission for files one by one because its a tedious task so help me which would happen dynamically via code for All folders so that i could iterate and get all file names .(I don't intend to get windows related files or kernal files ,just the user created files is enough)