windows-7 - Windows 7 在 "Program Files"中创建文件夹在 C# 代码中失败,即使我有管理员权限!

标签 windows-7 directory

我无法在 Windows 7 64 位计算机上的“程序文件”文件夹下使用 VS 2008 WPF C# 代码创建文件。我在以下代码中遇到的错误

        myFile = File.Create(logFile);

如下。 (这是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)

这似乎与 Windows 7 中的 UAC 有关,因为我的用户已经是计算机上的管理员,否则为什么我会得到这个?!

此外,由于 WinIOError 具有 SECURITY_ATTRIBUTES,我认为这与 Windows 7 中处理安全性的“新方式”有关。

我尝试浏览到“Program Files”文件夹,在该文件夹下将创建日志文件夹和文件。我可以手动创建文件夹,但是当我尝试创建文件时,我收到类似的“访问被拒绝”异常。

最佳答案

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

但是,您的程序在安装后不应向 Program Files 写入任何内容,安装更新时除外。
相反,您应该将日志文件存储在用户的应用程序数据文件夹中。

关于windows-7 - Windows 7 在 "Program Files"中创建文件夹在 C# 代码中失败,即使我有管理员权限!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709531/

相关文章:

c# - 适用于 .NET 开发的 Windows 7

python - 在 64 位 Windows 7 上使用 easy_install 时出现问题。 (找不到 python.exe)

delphi - TBrowseForFolder 所选行失去焦点

objective-c - 在 NSPopUpButton 中显示文件夹

python - 在Python中搜索带有扩展名的文件并复制到目录?

Python - 循环遍历不同文件夹中的文件

没有大量库依赖的 Python 消息框

windows-7 - "DIR *759*"不返回名称中包含 759 的文件。这是 Windows 7 的问题吗?

python - 如何在目录目录(python)中找到最近修改的文件夹?

java - 需要以管理员身份运行 Java 应用程序吗?