How can I create a temp file with a specific extension with .NET?

后端 未结 17 2108
北恋
北恋 2020-11-28 01:49

I need to generate a unique temporary file with a .csv extension.

What I do right now is

string filename = System.IO.Path.GetTempFileName().Replace(         


        
17条回答
  •  广开言路
    2020-11-28 02:09

    You can also alternatively use System.CodeDom.Compiler.TempFileCollection.

    string tempDirectory = @"c:\\temp";
    TempFileCollection coll = new TempFileCollection(tempDirectory, true);
    string filename = coll.AddExtension("txt", true);
    File.WriteAllText(Path.Combine(tempDirectory,filename),"Hello World");
    

    Here I used a txt extension but you can specify whatever you want. I also set the keep flag to true so that the temp file is kept around after use. Unfortunately, TempFileCollection creates one random file per extension. If you need more temp files, you can create multiple instances of TempFileCollection.

提交回复
热议问题