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

后端 未结 17 2095
北恋
北恋 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:28

    I mixed @Maxence and @Mitch Wheat answers keeping in mind I want the semantic of GetTempFileName method (the fileName is the name of a new file created) adding the extension preferred.

    string GetNewTempFile(string extension)
    {
        if (!extension.StartWith(".")) extension="." + extension;
        string fileName;
        bool bCollisions = false;
        do {
            fileName = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + extension);
            try
            {
                using (new FileStream(fileName, FileMode.CreateNew)) { }
                bCollisions = false;
            }
            catch (IOException)
            {
                bCollisions = true;
            }
        }
        while (bCollisions);
        return fileName;
    }
    

提交回复
热议问题