Windows 7 Create Folder in “Program Files” failing in C# code even thought I have admin rights!

萝らか妹 提交于 2019-12-13 15:49:16

问题


I am unable to create a file under "program files" folder on my Windows 7 64-bit machine in VS 2008 WPF C# code. The error I get on the following code

        myFile = File.Create(logFile);

is the following. (this is the innerException stack trace).

      at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.File.Create(String path)
   at MyFirm.MyPricingApp.UI.App.InitializeLogging() in C:\Projects\MyPricingApp\App.xaml.cs:line 150
   at MyFirm.MyPricingApp.UI.App.Application_Startup(Object sender, StartupEventArgs e) in C:\Projects\MyPricingApp\App.xaml.cs:line 38
   at System.Windows.Application.OnStartup(StartupEventArgs e)
   at System.Windows.Application.<.ctor>b__0(Object unused)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)

this seems like it has something to do with UAC in Windows 7, because why else would I get this since my user is already Admin on the machine ?!

Also since the WinIOError has SECURITY_ATTRIBUTES, I am thinking this has something to do with a "new way" security is handled in Windows 7.

I tried to browse to the "Program Files" folder, under which the log folder and file were to be created. I can create the folder by hand, but when i try to create the file, I get the similar "Access Denied" exception.


回答1:


Since UAC is enabled, programs do not run with administrative privileges, even though your account is an administrator.
In order to have administrative privileges, you need to right-click the application and click Run as Administrator.

However, your program should not write anything to Program Files after it's installed, except when installing updates.
Instead, you should store your log file in the user's Application Data folder.



来源:https://stackoverflow.com/questions/2709531/windows-7-create-folder-in-program-files-failing-in-c-sharp-code-even-thought

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!