Cannot create directory: System.UnauthorizedAccessException Error - c#

I am relatively new to using files and creating directories in C#, but I have been stuck for a while. I receive the following error: System.UnauthorizedAccessException: 'Access to the path 'C:\Program Files\Skyroom' is denied.'
Here is my code in case it helps:
if (File.Exists(#"C:\Program Files\Skyroom\gamedata.txt"))
{
Console.WriteLine("Game loading. Please wait..");
Thread.Sleep(500);
Console.Clear();
Console.WriteLine("Game loading. Please wait...");
Thread.Sleep(500);
Console.Clear();
Console.WriteLine("Game loading. Please wait.");
Thread.Sleep(500);
Console.Clear();
Console.WriteLine("Game loading. Please wait..");
Thread.Sleep(500);
Console.Clear();
Console.WriteLine("Game loading. Please wait...");
Thread.Sleep(500);
Console.Clear();
}
else
{
Directory.CreateDirectory(#"C:\Program Files\Skyroom");
File.Create(#"C:\Program Files\Skyroom\gamedata.txt");
Main();
}
Thank you. Any info needed, just ask.

You're getting that error because your app isn't running as administrator and is trying to write to Program Files which is for admins only.
Unless you're writing an installer, your application will never need to run as administrator so it can write to Program Files. Program files is not intended for applications to write runtime data to. It's a secure location intended for an administrator to install applications into. This process protects trusted application files from being maliciously changed.
You should not be writing your data to the ProgramFiles directory. Windows has a variety of directories for writing data to, such as %TEMP%, %APPDATA%, and %LOCALAPPDATA%.
Windows Environment Variables

Your problem is the windows user you are running the application under does not have permission to the folder C:\Program Files\Skyroom\.
You have a few options. One is to grant read/write permissions to the user at the time you create the directory:
var skyroomDirectory = Directory.CreateDirectory(#"C:\Program Files\Skyroom");
DirectorySecurity security = skyroomDirectory.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(#"MYDOMAIN\JohnDoe",
FileSystemRights.Modify,
AccessControlType.Allow));
skyroomDirectory.SetAccessControl(security);
File.Create(#"C:\Program Files\Skyroom\gamedata.txt");
Using the appropriate AccessControlType(s) for your needs. You should use the least amount of privilege necessary to perform the necessary tasks. https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights?view=netframework-4.7.2
Another option is to save the file in a user folder that the user will have permissions to. But the issue is a user will see a weird file and possibly delete it.

According to File.Create, An UnauthorizedAccessException means one of 2 things:
The caller does not have the required permission.
-or-
path specified a file that is read-only.
For Directory.CreateDirectory, it means:
The caller does not have the required permission.
I wouldn't create a directory under Program Files or Program File x(86). It is advisable to create under like C:\Users\ where you will have permissions.
If still need to create in program files, run visual studio as Administrator or change your manifest like below:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Related

Can't Add Full Control to Settings File

I have a C# application which stores it's settings in ProgramData subfolder such as
C:\ProgramData\Manufacturer\Product\Version\Settings.xml
I noticed that the application can't save settings changes, getting a permission denied error. My work-around was to manually change security settings and give Everyone full control on the folder tree and file. This works, but I'd like a more robust method.
Using suggestions from SO, I created the following code:
private void set_permissions()
{
try
{
// Create security idenifier for all users (WorldSid)
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
// get file info and add write, modify permissions
FileInfo fi = new FileInfo(settingsFile);
FileSecurity fs = fi.GetAccessControl();
FileSystemAccessRule fsar =
new FileSystemAccessRule(sid, FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow);
fs.AddAccessRule(fsar);
fi.SetAccessControl(fs);
LogIt.LogInfo("Set permissions on Settings file");
}
catch(Exception ex)
{
LogIt.LogError(ex.Message);
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
When I step through the code, I get
Attempted to perform an unauthorized operation exception
when I execute this statement:
fi.SetAccessControl(fs);
If I close Visual Studio 2015 and open it as administrator, then my code will execute properly and the file security now has an entry for Everyone with full control.
So finally, here comes the question:
I'm following suggestion of putting the above code in my application, then in the setup project I add a custom action to run the newly installed application with an Install command-line option. My application, if it sees "Install" argument, will run the above code. Since I'm using a setup project which installs for all users by default, it automatically gives the administrator prompt before install. Does that mean the entire session, including the special action to run the application after install, is running under administrator rights?
If so, this should work, right?
But if the person installing changes it to "This user" then it would not be running with admin rights, and my code will fail. If needed, I could always be the one to do the final install and therefore would always use the administrator prompt, but I hate to depend on that.
Is there a more proper way to do this?
Thanks...
It seems that your program is not running elevated and therefore cannot update files in that location, and I assume that you want your users to not require admin privilege that you could add using an elevation manifest in your program.
So why choose that location to store the data? Why not just use User's Application Data folder?
As for that code, it's probably more robust to add it as an installer class custom action rather than run an executable. In an Everyone install that runs elevated the code will run privileged with the local system account.

IIS 8( windows server 2012) cannot run batch file

Im hosting an asp.net application in IIS8 on windows server 2012.
this application suppose to execute an batch file.
it works perfect if i execute the application with visual studio in debug mode. but when i upload it to the IIS the application cant execute the batch file.
i tried to change the batch file with exe file. same problem.
the batch file suppose to execute from the application(WCF application) that in the IIS:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.WorkingDirectory = #"C:\path";
proc.StartInfo.FileName = #"C:\path\executer.bat";
proc.Start();
proc.Close();
please help,
Most likely the problem you are experiencing is due to permissions. You need to check what account the IIS Application Pool that your app is running under is configured for and whether that account has rights to run your batch file or the commands within that batch file.
When running in Visual Studio you're likely running IIS Express as the interactive user.
When running under IIS by default you're running under ApplicationPoolUser identity which has no rights to execute code, has no file access or anything else. Unless you've explicitly set a different account with appropriate file access rights to the batch file, and rights to execute the commands inside of the batch file, you won't be able to run the batch file from within IIS. To change that change the Application Pool user identity to a user that does have rights to both read and execute the batch file on disk and has any rights required to run what's executing in the batch file.
Make sure any folder or file accessed by your application have permissions granted to the AppPoolUser account. It is also important to check your applications resource folders too. For example, if you are writing logs, make sure you give the appPool user account enough permission to write to that file.
Your code is working fine . May be there is some issue in batch file i faced before .My batch file is
start "" BATCHLOG.exe
where BATCHLOG.exe is the executable
Some times batchfile named only
BATCHLOG.exe
does not work correctly on windows scheduler so may be in that case of yours

Getting permission for accessing an existing file in setup created using Inno Setup

I am a new C# programmer. I made a setup file of an application in Inno setup, but when I use this application after installation, the application crashes when it tries to access (read) an existing folder in the computer (which the user has permission to access otherwise). This folder does not contain any program file, or logs. It just contains some media files which are already in the computer.
I saw the Inno script format, but it shows only how to give permission to access program files/folders only, what about the files which are already there in the computer? Shouldn't the application should have access to files which the user (who installed it)has access to ?
To set permissions on existing files or folders, you can use the Windows cacls command in the [Run] section.
Filename: "{sys}\cacls.exe"; Parameters: """C:\My Folder\My File.ext"" /t /e /g ""Everyone"":f ""Power Users"":f ""Users"":f ""Authenticated Users"":f "; StatusMsg: "Configuring Windows settings..."; Flags: runhidden
Type cacls /? at a command prompt for all available switches and syntax.
It worked when I used
"Permissions: users-modify" in [Dirs] section.

Loss of admin privileges when Java program calls C# program to write to %ProgramData%

The scenario:
I have a Java based installer.
The Java based installer calls a C# program, whose job is to create a shortcut.
The shortcut location depends on if the installer is running as administrator or as a regular user. When running as admin, I'm trying to create a shortcut to "%ALLUSERSPROFILE%\Desktop", else I write to "%USERPROFILE%\Desktop".
My impression is that the issue seems to be a loss of administrative privilege when my Java program calls my C# shortcut maker program.
Notes:
I run my Java based installer as administrator (right click, run as administrator).
I'm able to verify the installer is running with administrator privileged because I can read registry keys that require administrative privilege.
I'm calling my C# program via 'Process process = Runtime.getRuntime().exec(command);'
When running the command manually through an administrative command prompt, the command works fine. (When outputting to "%ALLUSERSPROFILE%\Desktop")
When running the the same command manually, from a normal command prompt, I get System.UnauthorizedAccessException. (Which is to be expected). The program crashes in a similar was that it does when run from the installer.
The Exception:
Unhandled Exception: System.UnauthorizedAccessException: Access is
denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) at
IWshRuntimeLibrary.IWshShortcut.Save()
Any thoughts on what I'm missing? The installer needs to be flexible to run as both a normal user and as an administrator. How can I ensure this behavior?
Update 1
I attached a debugger to the C# program at runtime. It is throwing a:
DirectoryNoFoundException was unhandled
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)
I added "mkdir" commands before my shortcutmaker commands. The mkdir commands, just ensure that the directories exist before trying to write to them.
Rebuilt the installer, ran it and when trying to mkdir "%ALLUSERSPROFILE%\Desktop", java throws an exception of
java.io.IOException: Cannot run program "mkdir": CreateProcess error=2, The system cannot find the file specified
java.io.IOException: Cannot run program "mkdir": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
At this point, it looks like my process isn't getting admin access
Process process = Runtime.getRuntime().exec(command);
I'm going to see if I can find anything else.
Update 2
The following gave me some info that I tried: Enterprise Logging not translating environment variables in XML Trace Listener fileName specification
It suggested that %ALLUSERSPROFILE% was not getting translated.
Instead of %ALLUSERSPROFILE%, I got the environment variable values via:
String allUsersProfile = System.getenv("ALLUSERSPROFILE");
String userProfile = System.getenv("USERPROFILE");
I was then able to supply the actual values to the C# program. But I'm still having issues.
From a admin console I can navigate to "c:\ProgramData\Start Menu", but if I run "explorer" with administrative priviledges, I can navigate to "c:\ProgramData" but not see anything past that... Through some looking, I found out that "c:\ProgramData\Start Menu" is a protected operating system file. So I turned on the setting to see it. So now I can see it, but not go into it.
Using system internals, I elevated an explorer.exe to "system" access and still can't go into the folder (System internal elevation reference: http://verbalprocessor.com/2007/12/05/running-a-cmd-prompt-as-local-system/)
I right clicked on the folder and checked out the security tab. It looks like even my "System" user has limited access. I find this a bit baffling, that I can run the command from an admin command prompt that will write the shortcut to the desktop, but going through this other process I cannot... I also find the access to be a bit inconsistent.

Installing C# Windows Service on Windows 7

I have a batch file that I have been using to install my C# Windows Services for awhile now, never had a problem until Windows 7. I have attempted to run the batch file with Administrator privileges. I have attempted to run the command prompt with admin privs, navigate to the windows service EXE and run InstallUtil there. Still doesn't work.
After reading some other suggestions I tried moving my files out of the /bin folder and running them from another location but that also didn't work.
The batch file looks like this
#ECHO OFF
REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%
echo Installing IEPPAMS Win Service...
echo ---------------------------------------------------
InstallUtil /i IEPPAMS_WinService1.exe
echo ---------------------------------------------------
echo Done.
and I have a install log file that I dump info to. If I just double click the .bat file I get
Running a transacted installation.
Beginning the Install phase of the
installation. See the contents of the
log file for the
C:\Users\Justin\Desktop\service
test\IEPPAMS_WinService1.exe
assembly's progress. The file is
located at
C:\Users\Justin\Desktop\service
test\IEPPAMS_WinService1.InstallLog.
An exception occurred during the
Install phase.
System.InvalidOperationException:
Cannot open Service Control Manager on
computer '.'. This operation might
require other privileges. The inner
exception
System.ComponentModel.Win32Exception
was thrown with the following error
message: Access is denied.
The Rollback phase of the installation
is beginning. See the contents of the
log file for the
C:\Users\Justin\Desktop\service
test\IEPPAMS_WinService1.exe
assembly's progress. The file is
located at
C:\Users\Justin\Desktop\service
test\IEPPAMS_WinService1.InstallLog.
The Rollback phase completed
successfully.
The transacted install has completed.
When I run the .bat file with admin privileges nothing is written to the log file, and the service is still not installed.
Any thoughts? Is there a new way to install services in Windows 7?
Right click on the batch file and run it as Administrator.
You are most likely running into battle with the new security model (User Account Control) from Windows Vista and Windows 7. Even if you are running as an account that has Admin rights you will still need to elevate to do some (most) administrative activities. (Yes it is possible to disable this feature, but don't)
UAC (MSDN)
UAC (Wikipedia)
InstallUtil (MSDN)
Edit... The correct commandline is InstallUtil YourApp.exe. The /i does not look to be a vaild switch for InstallUtil.
So I was able to fix the problem by typing in the command line the entire path to InstallUtil and it worked. So after navigating to the folder that had my EXE I typed the following:
C:\Windows\Microsoft.NET\Framework\v4.0.21006\installutil.exe
IEPPAMS_WinService1.exe
Not sure why I have to do that in Windows 7 now when I never had to in XP, but oh well. Thanks for all the suggestions!
When I run the .bat file with admin privileges nothing is written to the log file, and the service is still not installed.
First off, you HAVE to run as admin permissions.
Second, when you "Run as Administrator", it actually changes the directory to c:\windows\system32 as the initial directory ( no idea why ), which would probably explain why running as admin causes no log file. Manually change to the path IEPPAMS_WinService1.exe resides in that the start of your script.

Categories

Resources