57

My application throws 'Access denied' errors when writing temporary files in the installation directory where the executable resides. However it works perfectly well in Windows XP. How to provide access rights to Program Files directory in Windows 7?

EDIT: How to make the program ask the user to elevate rights? (ie run program with full admin rights)

5
  • 6
    It does only work in XP if you haven't properly tested it (installed as Administrator, used by standard users). Stuff like that has been discouraged now for many years, you should fix your application instead of hacking around.
    – mghie
    Jun 3, 2009 at 18:46
  • 2
    Do you mean it is because I'm doing some shoddy coding? Is so, pls explain so that I can improve. Jun 3, 2009 at 18:51
  • 3
    Gergo Dries gives the correct answer below. Does your program actually need elevated privileges? Or are you trying to elevate privileges to support an unadvisable practice (i.e., writing temporary files to a directory where temporary files don't belong)?
    – Ben Dunlap
    Jun 3, 2009 at 18:59
  • 1
    You have a lot of correct answers already. I'm only saying that your assertion that "it works perfectly well in XP" is wrong, and probably comes from not testing your app under a limited account. Which you should do. You could try the Standard User Analyzer (technet.microsoft.com/de-de/library/cc766021(WS.10).aspx) to find the problematic areas of your application.
    – mghie
    Jun 3, 2009 at 19:05
  • thanks a lot for the suggestion. I understand that my xp installation had full admin privileges for the account i use. Jun 5, 2009 at 6:00

14 Answers 14

94

Your program should not write temporary files (or anything else for that matter) to the program directory. Any program should use %TEMP% for temporary files and %APPDATA% for user specific application data. This has been true since Windows 2000/XP so you should change your aplication.

The problem is not Windows 7.

You can ask for appdata folder path:

string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

or for TEMP path

string dir = Path.GetTempPath()
3
  • 4
    100% correct! More info here: social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/…
    – Greg Bray
    Aug 19, 2010 at 23:50
  • 9
    The problem with this answer is that it's not an answer at all, does windows knows the meaning of "backward compatibility"? if you created an application that was working well on windows XP why will it crash or even require any other specific new permissions to run on new systems, it's crazy to try to think of "maybe"s on your application in case MS decide that they will restrict X o Y now and your application relies on that. Instead MS should say "ok, you program files will be working as it's, but here's the NewProgramFiles folder which will help you to, blah blah blah".
    – Cross
    Aug 28, 2013 at 6:51
  • 11
    His questition was how to provide access rights. Your answer says bacicly, "don't". It, however does not answer his original question.
    – Cullub
    Sep 22, 2014 at 14:25
29

Your program has to run with Administrative Rights. You can't do this automatically with code, but you can request the user (in code) to elevate the rights of your program while it's running. There's a wiki on how to do this. Alternatively, any program can be run as administrator by right-clicking its icon and clicking "Run as administrator".

However, I wouldn't suggest doing this. It would be better to use something like this:

Environment.GetFolderPath(SpecialFolder.ApplicationData);

to get the AppData Folder path and create a folder there for your app. Then put the temp files there.

2
  • @n0vic3c0d3r I added a wiki reference for you. Hopefully that helps!
    – Joseph
    Jun 3, 2009 at 18:46
  • In case of errors add Enviroment: Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    – Troglo
    Jul 24, 2013 at 15:13
12

Options I can think of:

  • Run entire app as full admin priv. using UAC
  • Run a sub-process as full admin for only those things needing access
  • Write temporary files elsewhere
8

Add new item in the project: Application Manifest and save it.

Now open this file and look for <requestExecutionLevel>. It must be set to asInvoker.

Change it to highestAvailable. Now on executing your application, a prompt will appear asking for permission. Click yes!

Thats all :) now you can write and read from the system32 or any other file which requires admin right

You can verify your application by sigcheck.

sigcheck.exe -m yourapp.exe

And in the output check for element requestedExecutionLevel.

3
  • im not sure, it got couple of years for me to respond, Sorry for that :) Jul 17, 2019 at 14:29
  • Upvote because this is the answer. Because what if the application the person is asking about could be an installer that needs to write to program files?
    – JeffS
    Feb 3, 2020 at 14:12
  • Well that exactly my thought processed :) Feb 6, 2020 at 18:27
4

Another way round it would be to stop UAC then restart it. Create a CMD file with the following code;

Rem Stop UAC %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f rem force reboot Start ShutDown /R /F /T 30

You'll need to right click on the CMD file and use run as admin. once you have finished what you are doing restart UAC with the following code (no need to use run as admin this time);

%windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f

rem force reboot Start ShutDown /R /F /T 30

The down sides to using this method is have to right click and use run as admin to close UAC down and you have to reboot for it to take effect.

BTW there are several reasons why you would need to write to the forbidden areas...the first two that springs to mind would be to run a batch file to append host to prevent your browser going to dodgy sites or to copy license keys in a silent install.

1
  • 1
    This is the only answer that mentions that UAC can be involved in the denial of access, as opposed to just a lack of ACLs. Therefore it's the only answer which reflects on the operating systems part of the question. Dec 2, 2014 at 15:51
4

You can't cause a .Net application to elevate its own rights. It's simply not allowed. The best you can do is to specify elevated rights when you spawn another process. In this case you would have a two-stage application launch.

Stage 1 does nothing but prepare an elevated spawn using the System.Diagnostics.ProcessStartInfo object and the Start() call.

Stage 2 is the application running in an elevated state.

As mentioned above, though, you very rarely want to do this. And you certainly don't want to do it just so you can write temporary files into %programfiles%. Use this method only when you need to perform administrative actions like service start/stop, etc. Write your temporary files into a better place, as indicated in other answers here.

2

I cannot agree with arguments, that it is better to write all files in other directories, e.g., %APPDATA%, it is only that you cannot avoid it, if you want to avoid running application as administrator on Windows 7.

It would be much cleaner to keep all application specific data (e.g. ini files) in the same folder as the application (or in sub folders) as to speed the data all over the disk (%APPDATA%, registry and who knows where else). This is just Microsoft idea of clean programming. Than of course you need registry cleaner, disk cleaner, temporary file cleaner, ... instead of e+very clean practice - removing the application folder removes all application specific data (exep user data, which is normally somewhere in My Documents or so).

In my programs I would prefer to have ini files in application directory, however, I do not have them there, only because I cannot have them there (on Windows).

4
  • 4
    This practice is hardly unique to Windows. For example, the Unix paradigm of splitting file I/O into /bin, /var, /tmp, and /usr is several decades old. Also, the notion that placing files in the same filesystem directory will make them physically adjacent is terribly ignorant. Jul 11, 2010 at 3:19
  • -1 - I disagree with your disagreement. The problem is bad programmers who don't listen to the rules. Stay out of the Registry and you will never need a Registry Cleaner. Properly delete temporary files when you are finished with them and you will never need a Temp File Cleaner. Not having standard user access into various folders is the correct design, you don't want unauthorized people or malware messing around with certain OS and application folders. It is not difficult at all to follow the rules. I refuse to install software that fails to follow the rules.
    – deegee
    Aug 25, 2013 at 16:28
  • @RichardBerg Does Unix also generally prevent programs from writing to the directories where they are running from?
    – Dronz
    May 7, 2019 at 4:45
  • @Dronz yes. $ which git /usr/bin/git $ ls -ld /usr/bin drwxr-xr-x 2 root root 57344 Apr 25 22:44 /usr/bin May 8, 2019 at 13:50
1

I think there is an alternate solution to all these problems.... Make an two level application. As said above...

1) Launcher which will launch another Main App using code such as (VB)

Call ShellExecute(hwnd, "runas", App.Path & "\MainApp.exe", 0, 0, vbNormalFocus)

2) Main App, which is writing to protected areas, ie Program Files folder

I've successfully tried this with windows 7

I'm also developing an app which has online update feature. But it doesn't work in Vista/W7..

I agree with other peoples about Microsoft Policies and Standard Practices.

But my Question is .. 1) How to apply update to an existing application, which probably always remain in Program Files folder. 2) There might be some way to do this, otherwise how goolge updater, antivirus updater or any software updater workes?

I need answer to my questions..... :o

Prof. Rajendra Khope (MIT, Pune, India)

2
  • To Rajendra: To update your existing application (e.g. in c:\program files\your application), you need a seperate update program to do that. you need to elevate the updater program to runas administrator, in your updater, you can do whatever you want, like downloading files from Internet, replacing files in application folder. check the following link for how to elevate your program for launching. social.msdn.microsoft.com/Forums/en-US/windowssecurity/thread/…
    – user366184
    Jun 14, 2010 at 9:35
  • The question targets C# not VB
    – user8493486
    May 10, 2018 at 15:09
1

If you have such a program just install it in C:\, not in Program Files. I had a lot of problems when I was installing Android SDK. My problem got solved by installing it in C:\.

1

I was looking for answers. I found only one.

None of these work for me. I am not trying to write temporary files, unless this is defined as nonsystem files. Although I am designated the admin on my user profile, with full admin rights indicated in the UAC, I cannot write to program files or windows. This is very irritating.

I try to save an image found online directly to the windows/web/wallpaper folder and it won't let me. Instead, I must save it to my desktop (I REFUSE to navigate to "my documents/pictures/etc" as I refuse to USE such folders, I have my own directory tree thank you) then, from the desktop, cut and paste it to the windows/web/wallpaper folder. And you are telling me I should do that and smile? As an admin user, I SHOULD be able to save directly to its destination folder. My permissions in drive properties/security and in directory properties/security say I can write, but I can't. Not to program files, program files (86) and windows.

How about saving a file I just modified for a game in Program Files (86) (name of game) folder. It won't let me. I open the file to modify it, I can't save it without first either saving it to desktop etc as above, or opening the program which is used for modifying the file first as admin, which means first navigating all the way over to another part of the directory tree where I store those user mod programs, then within the program selecting to open file and navigate again to the file I could have just clicked on to modify in the first place from my projects folder, only to discover that this won't work either! It saves the file, but the file cannot be located. It is there, but invisible. The only solution is to save to desktop as above.

I shouldn't have to do all this as an admin user. However, if I use the true admin account all works fine. But I don't want to use the real admin account. I want to use a user account with admin rights. It says I have admin rights, but I don't.

And, finally, I refuse to store my portables in %appdata%. This is not how I wish to navigate through my directory tree. My personal installations which I use as portables are stored in the directory I create as a navigation preference.

So, here is the tried and true answer I have found:

From what I have seen so far.... unless one uses the real admin account, these permissions just aren't ever really available to any other user with admin privileges in the Windows Vista and Windows 7 OS's. While it was simple to set admin privileges in Windows XP, later versions have taken this away for all but those who can comfortably hack around.

1
  • 1
    Please edit your answer, to make the part which actually answers (the very last paragraph, I think) more prominent. The larger part of your answer seems reasoning why you think that this it the only answer. Adding that might make some sense, the way you structured your answer however puts you in danger of getting "not-an-answer" flags. In my opinion, you should also reduce the reasoning part drastically. Otherwise welcome to StackOverflow and thanks for trying to help. Take the tour at your convenience, for getting lots of helpful information on how things work here.
    – Yunnosch
    Dec 17, 2017 at 8:12
1

While M$ "best practices" is to not write data into the %programfiles% folder; I sometimes do. I do not think it wise to write temporary files into such a folder; as the TEMP environment variable might e.g. point to a nice, fast, RAM drive.

I do not like to write data into %APPDATA% however. If windows gets so badly messed up that one needs to e.g. wipe it and reinstall totally, perhaps to a different drive, you might lose all your settings for nearly all your programs. I know. I've done it many times. If it is stored in %programfiles%, 1) it doesn't get lost if I e.g. have to re-install Windows on another drive, since a user can simply run the program from its directory, 2) it makes it portable, and 3) keeps programs and their data files together.

I got write access by having my installer, Inno Setup, create an empty file for my INI file, and gave it the users-modify setting in the [Files] section. I can now write it at will.

6
  • 4
    -1 - Don't store settings files in ProgramFiles. Ever. If Windows needs to be totally wiped then everything in ProgramFiles is wiped as well, so your argument is wrong. Your app should always re-create its default settings file (ini, xml, etc.) in the AppData folder on a new install. If I ever install an app that does not follow the rules, it gets uninstalled and never used again.
    – deegee
    Aug 25, 2013 at 16:09
  • 1
    @deegeem Program Files does NOT get wiped when re-installing Windows. Putting app settings in the same folder as the executable has merit for the reasons specified above. Microsoft's "best practices" for this stem from security and avoiding access permission security holes. Writing to the app install folder doesn't mean you will have a security flaw, but it could be more likely.
    – syplex
    Apr 2, 2015 at 21:01
  • 1
    Writing to the program files folder makes an app portable. It's also really nice if yer registry ever gets trashed, or you reinstall windows. I would copy the apps in Program Files that were portable, and reinstall Windows; although deegeem says they don't get trashed. That may change. That way, my settings would be preserved.
    – CodeLurker
    Aug 17, 2016 at 20:48
  • 1
    I have an app that can share data between all users, being installed in the %programfiles% folder, or for individual users, in %appdata% - more due to the limitations of users running a user account than an admin acct. I myself like being able to go into "Program Files" and see what is installed on a machine; for space management purposes and just general information. Whether I install to %programfiles% or %programData%, I can give all users access to data directories I create as a user, and to I see no permissions advantage to the latter (if the reason for your downvote), except M$ says so.
    – CodeLurker
    May 25, 2017 at 14:24
  • 1
    Actually, there is probably no need for an %appdata% install, since I can indeed create directories in %programFiles% that all users can access, installing from a user acct.
    – CodeLurker
    May 25, 2017 at 14:52
0

I am working on a program that saves its data properly to %APPDATA%, but sometimes, there are system-wide settings that affect all users. So in these situations, it HAS to write to the programs installation directory.

And as far as I have read now, it's impossible to temporarily get write access to one directory. You can only run the whole application as administrator (which should be out of the question) or not be able to save that file. (all or nothing)

I guess, I will just write the file to %APPDATA% and launch an external program that copies the file into the installation folder and have THAT program demand admin privileges... dumb idea, but seems to be the only practical solution...

1
  • 2
    For system-wide settings that affect all users, store the file(s) in CommonApplicationData. See MSDN Environment.SpecialFolders page: link and see: link
    – deegee
    Aug 25, 2013 at 16:37
0

You can add an access to IIS User for folders of Website or Web Application that you want write or rewrite in it.

-5

It would be neater to create a folder named "c:\programs writable\" and put you app below that one. That way a jungle of low c-folders can be avoided.

The underlying trade-off is security versus ease-of-use. If you know what you are doing you want to be god on you own pc. If you must maintain healthy systems for your local anarchistic society, you may want to add some security.

1
  • I agree, this is not a great suggestion at all. Nov 7, 2013 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.