Change image permission in c# - c#

I have a picturebox which I loaded an image. I dont want to change the dimensions of the picturebox. I want to be able to change images width and height but for that I need to change its permissions from readonly to read-write. How can i do that programmatically?
Thanks!

try this:
using System.Security.AccessControl;
-
private void SetFullAccessAttribute(string fileName)
{
string path = fileName;
DirectorySecurity sec = Directory.GetAccessControl(path);
System.Security.Principal.SecurityIdentifier everyone = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(path, sec);
}
P.S. in order to successfully execute the code above, you should be running your application in elevated permissions

Related

Cannot set Full Control permission for folder

I'm trying to add the Full Control permission (for a NT service account) to a folder through C#. However, the permission is not set, what I am missing here?
var directoryInfo = new DirectoryInfo(#"C:\Test");
var directorySecurity = directoryInfo.GetAccessControl();
directorySecurity.AddAccessRule(new FileSystemAccessRule("NT Service\\FileMoverService",
FileSystemRights.FullControl, AccessControlType.Allow));
directoryInfo.SetAccessControl(directorySecurity);
You need to specify the inheritance flags:
directorySecurity.AddAccessRule(new FileSystemAccessRule(#"NT Service\FileMoverService",
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
The method GrantFullControl can be used to set the Full Control permission for a given directory and user.
private static void GrantFullControl(string directoryPath, string username)
{
if (!Directory.Exists(directoryPath))
return;
var directorySecurity = Directory.GetAccessControl(directoryPath);
directorySecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None,
AccessControlType.Allow));
Directory.SetAccessControl(directoryPath, directorySecurity);
}
Just call the method as shown below.
GrantFullControl(#"C:\Test", #"NT Service\FileMoverService");

Programmatic created folder with ACL not accessible

I had a lot of pain programmatic creating a folder with ACL and owner..
Taks:
Create a folder only accessible by one user (not even Administrator).
(current) Solution:
Run as Admin:
// path is the directory, "target" the parent directory
String path = Path.Combine(target, "Data");
DirectorySecurity ds = Directory.GetAccessControl(target);
// up is the "UserPrincipal"
ds.AddAccessRule(new FileSystemAccessRule(up.Sid, FileSystemRights.CreateDirectories, AccessControlType.Allow));
Directory.SetAccessControl(target, ds);
// safeTokenHandle_SecureUser is the token of the already logged in User stored in "up"
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle_SecureUser.DangerousGetHandle()))
{
ds = new DirectorySecurity();
// Set owner only works impersonated
ds.SetOwner(up.Sid);
// Inherited needs impersonation
ds.AddAccessRule(new FileSystemAccessRule(up.Sid, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
// Add Backupgroup
ds.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier("S-1-5-32-551"), FileSystemRights.Read, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
DirectoryInfo directory = Directory.CreateDirectory(path, ds);
}
Problem:
Path created in "C:\temp\Sec53" (jea, count my tries.. but multiple tries are i the same directory..)
c:\temp\Sec53>whoami
pc-XXX\YYYuser93
c:\temp\Sec53>dir /q (1)
Datenträger in Laufwerk C: ist Windows
Volumeseriennummer: ...
Verzeichnis von c:\temp\Sec53
13.02.2019 13:13 <DIR> VORDEFINIERT\Administra. (2)
13.02.2019 13:13 <DIR> AAA\BBB ..
13.02.2019 13:13 <DIR> XXX\YYYUser93 Data
(TRIM)
c:\temp\Sec53>cacls *
c:\temp\Sec53\Data VORDEFINIERT\Sicherungs-Operatoren:(OI)(IO)(Beschränkter Zugriff:) (3)
READ_CONTROL
SYNCHRONIZE
FILE_GENERIC_READ
FILE_READ_DATA
FILE_READ_EA
FILE_READ_ATTRIBUTES
XXX\YYYUser93:(OI)(IO)F
(TRIM)
c:\temp\Sec53>cd Data
Zugriff verweigert (4)
"Dir /q" shows the owner
User is: Predefined / Administrator
User is: Predefined / Backup operator group
Tranlated: Access denied
You can see, I'm logged in CMD with this user. The directory exists and the owner is the user. Permissions to this user are set to Full. But I'm still not able to change in this directory.
What is wrong? WTF? What can I do?
Got it, at try number 75..
two rules needed, one for current object, one for inherited..
ds.AddAccessRule(new FileSystemAccessRule(up.Sid, FileSystemRights.FullControl, AccessControlType.Allow));
ds.AddAccessRule(new FileSystemAccessRule(up.Sid, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
In the question I only create the inherited rule (with wrong Flags).

Set permissions for directorys/subdirectorys/files

I want to be able to set the persmissions for subfolders and files inside a targeted folder for a specific user.
Up until now i found out how to set the permissions for a specific folder. But not for subfolders and files inside the original folder.
After extensive internet search i could not find any clue on how to tackle this problem. Also the windows doku just shows how to set permission for only a directory.
class DirectoryPermissions
{
public static void DirectoryPermissionsMain(string Directory, string Account, string Rights, int Takeaway, string Domain)
{
try
{
string DirectoryName = Directory;
Console.WriteLine("Adding access control entry for " + DirectoryName);
if(Takeaway == 0 && Rights.Equals("Read")){
AddDirectorySecurity(DirectoryName, Domain + #"\" + Account, FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Removing access control entry from " + DirectoryName);
}
MessageBox.Show("Done");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
// Adds an ACL entry on the specified directory for the specified account.
public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
// Create a new DirectoryInfo object.
DirectoryInfo dInfo = new DirectoryInfo(FileName);
// Get a DirectorySecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = dInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
dInfo.SetAccessControl(dSecurity);
}
}
I hope one of you can point me in the right direction.
You have to add another AccessRule with InheritanceFlags set to ContainerInherit AND ObjectInherit.
To get the permissions to propgate to child folders, the PropagationFlag is set to Inherit only.
Here's an example below
public void PropogateSecurity(string userid,string directory)
{
var myDirectoryInfo = new DirectoryInfo(directory);
var myDirectorySecurity = myDirectoryInfo.GetAccessControl();
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(userid, FileSystemRights.Modify, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(userid, FileSystemRights.Modify, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
You can also do this with recursion, but the above would be my preferred method as cleaning up permissions would be annoying.

C# - Modify File Permission ASP.NET MVC

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

Change permissions of folders

I want to change some folder permissions (set to Read-Only) to ReadWriteExecute!
I wrote this code, but the folder permission is still Read-Only:
private void ChangePermissions(string folder)
{
string userName = Environment.UserName;
FileSystemAccessRule accessRule = new FileSystemAccessRule(userName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit
| InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
DirectoryInfo directoryInfo = new DirectoryInfo(folder);
DirectorySecurity directorySec = directoryInfo.GetAccessControl();
directorySec.AddAccessRule(accessRule);
directoryInfo.SetAccessControl(directorySec);
}
If I want delete this directory with Directory.Delete(folder, true) I get this error message:
"Access to the path 'entries' is denied."
Sure, the permissions are still Read-Only!
What is wrong here?
You could try something like this:
var dirInfo = new DirectoryInfo(folder);
dirInfo.Attributes &= ~FileAttributes.ReadOnly;
This uses the bitwise logical AND operator (&=) to append to the existing Attributes property the inverse of FileAttributes.ReadOnly (because ~ is bitwise NOT).

Categories