在 .NET 2.0 中,在 Vista/Windows 7 中将文件保存到桌面 [英] Save File to Desktop in Vista/Windows 7 in .NET 2.0

查看:14
本文介绍了在 .NET 2.0 中,在 Vista/Windows 7 中将文件保存到桌面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在更新我们的一个应用程序.它必须使用 .NET 2.0.一部分使用

I'm working on updating one of our applications. It must use .NET 2.0. One portion creates a file on the Desktop using

FileStream fs = new FileStream(Environment.GetFolderPath
    (Environment.SpecialFolder.DesktopDirectory), FileMode.Create);

但是我在 Windows 7 中遇到了 UnauthorizedAccessException(我假设还有 Vista,但我还没有测试过).我查看了提升(不是针对整个程序,而是针对将创建文件并对其执行操作的单独程序集);但是,这似乎需要 .NET 3.0 或 3.5.有没有办法使用 .NET 2.0 访问桌面文件夹?(要求以管理员身份运行程序也不是一种选择)

But I get an UnauthorizedAccessException in Windows 7 (and Vista too, I'm assuming, though I haven't tested that yet). I looked into elevation (not for the entire program, but for a separate assembly which would create the file and perform actions on it); however that seems to require .NET 3.0 or 3.5. Is there any way to gain access to the Desktop folder using .NET 2.0? (Requiring the program to be run as an Administrator is also not an option)

(我进行了搜索,唯一接近我要问的问题是:标准帐户 (Vista) 中的文件创建失败 但是它正在谈论提升整个应用程序并且不是特定于 .NET 2.0,所以我相信这不是重复的)

(I did a search, and the only question close to what I'm asking is this: File creation fails in standard account (Vista) however it is talking about elevating the entire app and is not .NET 2.0 specific, so I believe this isn't a duplicate)


哇,我真的傻了.这实际上工作正常.我试图创建一个名为 C:UsersMyUserDesktop 的文件.哎呀.抱歉造成混乱.


Wow, I was being really dumb. This actually works fine. I was trying to create a file called C:UsersMyUserDesktop. Oops. Sorry for the confusion.

这是例外的文本:

  System.UnauthorizedAccessException was unhandled
  Message="Access to the path 'C:\Users\MyUser\Desktop' is denied."
  Source="mscorlib"
  StackTrace:
       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, String msgPath, Boolean bFromProxy)
       at System.IO.FileStream..ctor(String path, FileMode mode)
       at MyProgram.Prog.SaveDiagnostic(String filename, String text) in C:SourceMyProgramProg.cs:line 95
       at MyProgram.Form1.buttonGenDiagnostic_Click(Object sender, EventArgs e) in C:SourceMyProgramForm1.cs:line 4729
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Northwoods.CRM.Import.Form1.Main(String[] args) in I:WebProspectSourceNorthwoods.CRM.ImportForm1.cs:line 2616
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

推荐答案

问题出在这段代码

FileStream fs = new FileStream(Environment.GetFolderPath
    (Environment.SpecialFolder.DesktopDirectory), FileMode.Create);

我们把它改写成实际会发生的步骤

Let's rewrite it into the steps that actually will occur

var desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
var fs = new FileStream(desktopFolder, FileMode.Create);

您在这里尝试做的不是在桌面上创建文件,而是尝试创建桌面文件夹本身.桌面文件夹显然已经存在,所以你得到一个错误.

What you're trying to do here is not create a file on the desktop, you are trying to create the desktop folder itself. The desktop folder obviously already exists, so you get an error.

您需要做的是在桌面文件夹创建一个文件.你可以使用 Path.Combine 来做到这一点,就像这样:

What you need to do is create a file inside the desktop folder. You can use Path.Combine to do this, like this:

var desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
var fullFileName = Path.Combine(desktopFolder, "Test.txt");
var fs = new FileStream(fullFileName, FileMode.Create);

您可能还想将 FileMode 更改为 OpenOrCreate,或处理您的异常 - 例如,如果代码运行了两次,并且该文件在第二次尝试时已经存在,所以您不会能够再次创建它

You may also want to change the FileMode to OpenOrCreate, or handle your exceptions - if for example the code runs twice, and the file will already exist on the second try, so you won't be able to create it a second time

这篇关于在 .NET 2.0 中,在 Vista/Windows 7 中将文件保存到桌面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆