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
Related
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);
Hy,
is there any posibillities to restrict acces to a folder stored on an sd card?
I tried this but it doesn't work...Any ideas are welcome.
Thanks...
public static void setRight(string dirName,string account, FileSystemRights rights, AccessControlType controlType)
{
DirectoryInfo dir = new DirectoryInfo(dirName);
DirectorySecurity dSecurity = new DirectorySecurity();// Directory.GetAccessControl(dirName);
// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
// Set the new access settings.
dir.SetAccessControl(dSecurity);
Directory.SetAccessControl(dirName, dSecurity);
}
Try using the File.Encrypt and File.Decrypt methods. You can use recursion to encrypt directories, by encrypting all files in them.
Hello everyone and well met! I have tried a lot of different methods/programs to try and solve my problem. I'm a novice programmer and have taken a Visual Basic Class and Visual C# class.
I'm working with this in C#
I started off by making a very basic move file program and it worked fine for one file but as I mentioned I will be needing to move a ton of files based on name
What I am trying to do is move .pst (for example dave.pst) files from my exchange server based on username onto a backup server in the users folder (folder = dave) that has the same name as the .pst file
The ideal program would be:
Get files from the folder with the .pst extension
Move files to appropriate folder that has the same name in front of the .pst file extension
Update:
// String pstFileFolder = #"C:\test\";
// var searchPattern = "*.pst";
// var extension = ".pst";
//var serverFolder = #"C:\test3\";
// String filename = System.IO.Path.GetFileNameWithoutExtension(pstFileFolder);
// Searches the directory for *.pst
DirectoryInfo sourceDirectory = new DirectoryInfo(#"C:\test\");
String strTargetDirectory = (#"C:\test3\");
Console.WriteLine(sourceDirectory);
Console.ReadKey(true);>foreach (FileInfo file in sourceDirectory.GetFiles()) {
Console.WriteLine(file);
Console.ReadKey(true);
// Try to create the directory.
System.IO.Directory.CreateDirectory(strTargetDirectory);
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
This is just a simple copy procedure. I'm completely aware. The
Console.WriteLine(file);
Console.ReadKey(true);
Are for verification purpose right now to make sure I'm getting the proper files and I am. Now I just need to find the folder based on the name of the .pst file(the folder for the users are already created), make a folder(say 0304 for the year), then copy that .pst based on the name.
Thanks a ton for your help guys. #yuck, thanks for the code.
Have a look at the File and Directory classes in the System.IO namespace. You could use the Directory.GetFiles() method to get the names of the files you need to transfer.
Here's a console application to get you started. Note that there isn't any error checking and it makes some assumptions about how the files are named (e.g. that they end with .pst and don't contain that elsewhere in the name):
private static void Main() {
var pstFileFolder = #"C:\TEMP\PST_Files\";
var searchPattern = "*.pst";
var extension = ".pst";
var serverFolder = #"\\SERVER\PST_Backup\";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) {
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Gets the user name based on file name
// e.g. DaveSmith.pst would become DaveSmith
var userName = theFileInfo.Name.Replace(extension, "");
// Sets up the destination location
// e.g. \\SERVER\PST_Backup\DaveSmith\DaveSmith.pst
var destination = serverFolder + userName + #"\" + theFileInfo.Name;
File.Move(file, destination);
}
}
System.IO is your friend in this case ;)
First, Determine file name by:
String filename = System.IO.Path.GetFileNameWithoutExtension(SOME_PATH)
To make path to new folder, use Path.Combine:
String targetDir = Path.Combine(SOME_ROOT_DIR,filename);
Next, create folder with name based on given fileName
System.IO.Directory.CreateDirectory(targetDir);
Ah! You need to have name of file, but with extension this time. Path.GetFileName:
String fileNameWithExtension = System.IO.Path.GetFileName(SOME_PATH);
And you can move file (by File.Move) to it:
System.IO.File.Move(SOME_PATH,Path.Combine(targetDir,fileNameWithExtension)
Laster already show you how to get file list in folder.
I personally prefer DirectoryInfo because it is more object-oriented.
DirectoryInfo sourceDirectory = new DirectoryInfo("C:\MySourceDirectoryPath");
String strTargetDirectory = "C:\MyTargetDirectoryPath";
foreach (FileInfo file in sourceDirectory.GetFiles())
{
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
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)
I'm working on an application which stores some files in the CommonApplicationData folder. My application has to modify these files. I managed to create a custom action to grant fullcontrol rights to my application folder in the CommonApplicationData folder. But this didn't solve the problem for non-admin users. When I log on as a user and try to modify one of these files, I get the "Access Denied" message.
How can I solve this problem? Thanks.
Here is the code which I used in the Custom Action:
public void GetUsers()
{
SelectQuery sQuery = new SelectQuery("Win32_UserAccount", "Domain='" + System.Environment.UserDomainName.ToString() + "'");
try
{
ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
foreach (ManagementObject mObject in mSearcher.Get())
{
Permission(mObject["Name"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void Permission(string user)
{
string directory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string CompanyFolderPath = Path.Combine(directory, "naseelco\\lms2004");
DirectoryInfo myDirectoryInfo = new DirectoryInfo(CompanyFolderPath);
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
string User = System.Environment.UserDomainName + "\\" + user;
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, FileSystemRights.FullControl, AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
EDIT:
For those who would like to know the solution for this problem:
Instead of granting Access Rights to the parent folder, the individual files int that folder are granted Access Rights for each user. The Permission method in the code above has been modified as follows:
private void Permission(string user)
{
string directory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string filePath = Path.Combine(directory, "naseelco\\lms2004\\fms.txt");
FileSecurity fSecurity = File.GetAccessControl(filePath);
FileSystemAccessRule rule = new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow);
fSecurity.SetAccessRule(rule);
File.SetAccessControl(filePath, fSecurity);
}
A good solution is to grant full control to Everyone using xcacls.exe or any other ACL tool. This tool can be added as a custom action in your setup project.
Granting privileges to each user is not recommended because future accounts will not be covered. Also, doing this through custom code doesn't always work. Windows permissions are a bit tricky when it comes to controlling them through code.