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

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

    Based on answers I found from the internet, I come to my code as following:

    public static string GetTemporaryFileName()
    {       
        string tempFilePath = Path.Combine(Path.GetTempPath(), "SnapshotTemp");
        Directory.Delete(tempFilePath, true);
        Directory.CreateDirectory(tempFilePath);
        return Path.Combine(tempFilePath, DateTime.Now.ToString("MMddHHmm") + "-" + Guid.NewGuid().ToString() + ".png");
    }
    

    And as C# Cookbook by Jay Hilyard, Stephen Teilhet pointed in Using a Temporary File in Your Application:

    • you should use a temporary file whenever you need to store information temporarily for later retrieval.

    • The one thing you must remember is to delete this temporary file before the application that created it is terminated.

    • If it is not deleted, it will remain in the user’s temporary directory until the user manually deletes it.

提交回复
热议问题