IronSlug
IronSlug

Reputation: 492

How to run portion of code in lower execution level

I develop a Console App in C# which needs to run as administrator (required by some calls to sqllocaldb.exe and sqlcmd.exe), so my app.manifest has this line :

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

At some point I create a directory with

Directory.CreateDirectory("mypath");

Then copy some .mdf file that I later use in SqlCmd to create a database. My problem is that as the directory is created as administrator the file I copy is restricted in write access and thus provoke an exception in sqlserver : Database [Database_Name] cannot be upgraded because it is read-only or has read-only files

Is it possible to run the portion of code that do the directory creation / file copying as a simple user ?
OR
Can I specifically create my directory with no protected access ?

NOTE : I've looked in the DirectorySecurity / FileSecurity stuff, but the FileSystemAccessRule constructor needs to be passed the account name as a string, problem : I don't know the account name / group name of my user. So I could use "Everyone", but what if my user's system is set to French (as I am) or German ?

Upvotes: 4

Views: 107

Answers (1)

Magnus
Magnus

Reputation: 46947

You can set the "Everyone" right like this without knowing the culture.

var sec = Directory.GetAccessControl(path);
var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(path, sec);

Upvotes: 4

Related Questions