Windows 7在"程序文件"中创建文件夹在C#代码中失败,即使我认为我有管理员权限!

Shi*_*iva 2 directory windows-7

我无法在VS 2008 WPF C#代码中的Windows 7 64位计算机上的"program files"文件夹下创建文件.我得到以下代码的错误

        myFile = File.Create(logFile);
Run Code Online (Sandbox Code Playgroud)

如下.(这是innerException堆栈跟踪).

      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)
Run Code Online (Sandbox Code Playgroud)

这似乎与Windows 7中的UAC有关,因为为什么我会得到这个,因为我的用户已经是机器上的Admin?

此外,由于WinIOError具有SECURITY_ATTRIBUTES,我认为这与在Windows 7中处理"新方式"安全性有关.

我试图浏览到"Program Files"文件夹,在该文件夹下创建日志文件夹和文件.我可以手动创建文件夹,但是当我尝试创建文件时,我得到了类似的"拒绝访问"异常.

SLa*_*aks 6

由于启用了UAC,因此即使您的帐户是管理员,程序也不会以管理员权限运行.
要获得管理权限,您需要右键单击该应用程序,然后单击以管理员身份运行.

但是,除非安装更新,否则程序在安装后不应向Program Files写入任何内容.
相反,您应该将日志文件存储在用户的Application Data文件夹中.