Writing File to Temp Folder

后端 未结 5 898
别那么骄傲
别那么骄傲 2020-12-08 13:14

I want to use StreamWriter to write a file to the temp folder.

It might be a different path on each PC, so I tried using %temp%\\SaveFile.txt

相关标签:
5条回答
  • 2020-12-08 13:16

    The Path class is very useful here.
    You get two methods called

    Path.GetTempFileName

    Path.GetTempPath

    that could solve your issue

    So for example you could write: (if you don't mind the exact file name)

    using(StreamWriter sw = new StreamWriter(Path.GetTempFileName()))
    {
        sw.WriteLine("Your error message");
    }
    

    Or if you need to set your file name

    string myTempFile = Path.Combine(Path.GetTempPath(), "SaveFile.txt");
    using(StreamWriter sw = new StreamWriter(myTempFile))
    {
         sw.WriteLine("Your error message");
    }
    
    0 讨论(0)
  • 2020-12-08 13:21

    You can dynamically retrieve a temp path using as following and better to use it instead of using hard coded string value for temp location.It will return the temp folder or temp file as you want.

    string filePath = Path.Combine(Path.GetTempPath(),"SaveFile.txt");
    

    or

    Path.GetTempFileName();
    
    0 讨论(0)
  • 2020-12-08 13:23

    For %appdata% take a look to

    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    
    0 讨论(0)
  • 2020-12-08 13:29
    string result = Path.GetTempPath();
    

    https://docs.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath

    0 讨论(0)
  • 2020-12-08 13:37
    System.IO.Path.GetTempPath()
    

    The path specified by the TMP environment variable. The path specified by the TEMP environment variable. The path specified by the USERPROFILE environment variable. The Windows directory.

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