Windows temporary files behaviour - are they deleted by the system?

前端 未结 7 2118
广开言路
广开言路 2020-12-15 03:28

Using the .net framework you have the option to create temporary files with

Path.GetTempFileName(); 

The MSDN doesn\'t tell us what happens

相关标签:
7条回答
  • 2020-12-15 04:03

    I've read on the internet a lot of times that people don't want to use Path.GetTempFileName because they say it could return an already existing file, to solve the problem you can make a filename based on a GUID.

    This Function solves that Problem: Iterates until it finds a nonexistent file name with an specific extension.

    VB.net

    Public Shared Function GetTempFileName(ByVal extensionWithDot As String) As String
        Dim tempFileName As String
        Do
            tempFileName = System.IO.Path.GetTempFileName
            If extensionWithDot IsNot Nothing Then
                tempFileName = tempFileName.Replace(System.IO.Path.GetExtension(tempFileName), extensionWithDot)
            End If
        Loop While System.IO.File.Exists(tempFileName)
        Return tempFileName
    End Function
    

    C#:

    public static string GetTempFileName(string extensionWithDot)
    {
        string tempFileName = null;
        do {
            tempFileName = System.IO.Path.GetTempFileName;
            if (extensionWithDot != null) {
                tempFileName = tempFileName.Replace(System.IO.Path.GetExtension(tempFileName), extensionWithDot);
            }
        } while (System.IO.File.Exists(tempFileName));
        return tempFileName;
    }
    

    Note: I use argument extensionWithDot because System.IO.Path.GetExtension returns with dot.

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