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

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

    Easy Function in C#:

    public static string GetTempFileName(string extension = "csv")
    {
        return Path.ChangeExtension(Path.GetTempFileName(), extension);
    }
    
    0 讨论(0)
  • 2020-11-28 02:26

    Why not checking if the file exists?

    string fileName;
    do
    {
        fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
    } while (System.IO.File.Exists(fileName));
    
    0 讨论(0)
  • 2020-11-28 02:27
    public static string GetTempFileName(string extension)
    {
      int attempt = 0;
      while (true)
      {
        string fileName = Path.GetRandomFileName();
        fileName = Path.ChangeExtension(fileName, extension);
        fileName = Path.Combine(Path.GetTempPath(), fileName);
    
        try
        {
          using (new FileStream(fileName, FileMode.CreateNew)) { }
          return fileName;
        }
        catch (IOException ex)
        {
          if (++attempt == 10)
            throw new IOException("No unique temporary file name is available.", ex);
        }
      }
    }
    

    Note: this works like Path.GetTempFileName. An empty file is created to reserve the file name. It makes 10 attempts, in case of collisions generated by Path.GetRandomFileName();

    0 讨论(0)
  • 2020-11-28 02:27

    How about:

    Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString() + "_" + Guid.NewGuid().ToString() + ".csv")
    

    It is highly improbable that the computer will generate the same Guid at the same instant of time. The only weakness i see here is the performance impact DateTime.Now.Ticks will add.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题