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

前端 未结 1 374
梦谈多话
梦谈多话 2020-12-18 08:15

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(Env         


        
相关标签:
1条回答
  • 2020-12-18 08:39

    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

    0 讨论(0)
提交回复
热议问题