Get/open temp file in .NET

后端 未结 4 1060
青春惊慌失措
青春惊慌失措 2021-01-17 12:01

I would like to do something like the below. What function returns me an unique file that is opened? so i can ensure it is mine and i wont overwrite anything or write a comp

相关标签:
4条回答
  • 2021-01-17 12:32

    You can do something like this:

    var path = Path.GetTempFileName();
    var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
    var writer = new BinaryWriter(stream);
      ...
    
    0 讨论(0)
  • 2021-01-17 12:34

    Another alternative is the TempFileCollection class. It provides an IDisposable wrapper much like what is suggested in the docs for Path.GetTempFileName().

    0 讨论(0)
  • 2021-01-17 12:36

    There are two methods for this:

    • Path.GetTempFileName

      This will create a temporary file and return its name.

    • Path.GetRandomFileName

      This will use a cryptographically strong, random string as file name and won't create the file for you.

    Usually the first method suffices; the documentation for GetRandomFileName says:

    When the security of your file system is paramount, this method should be used instead of GetTempFileName.

    0 讨论(0)
  • 2021-01-17 12:36

    Can use the GetTempFileName() method to obtain a fairly unique temporary file name.

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