Save File to Desktop in Vista/Windows 7 in .NET 2.0

↘锁芯ラ 提交于 2019-11-29 07:26:28

The problem is in this code

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.

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);

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

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