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

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

    This is what I am doing:

    string tStamp = String.Format("{0:yyyyMMdd.HHmmss}", DateTime.Now);
    string ProcID = Process.GetCurrentProcess().Id.ToString();
    string tmpFolder = System.IO.Path.GetTempPath();
    string outFile = tmpFolder + ProcID + "_" + tStamp + ".txt";
    
    0 讨论(0)
  • 2020-11-28 02:05

    This is a simple but effective way to generate incremental filenames. It will look in the current directly (you can easily point that somewhere else) and search for files with the base YourApplicationName*.txt (again you can easily change that). It will start at 0000 so that the first file name will be YourApplicationName0000.txt. if for some reason there are file names with junk between (meaning not numbers) the left and right parts, those files will be ignored by virtue of the tryparse call.

        public static string CreateNewOutPutFile()
        {
            const string RemoveLeft = "YourApplicationName";
            const string RemoveRight = ".txt";
            const string searchString = RemoveLeft + "*" + RemoveRight;
            const string numberSpecifier = "0000";
    
            int maxTempNdx = -1;
    
            string fileName;
            string [] Files = Directory.GetFiles(Directory.GetCurrentDirectory(), searchString);
            foreach( string file in Files)
            {
                fileName = Path.GetFileName(file);
                string stripped = fileName.Remove(fileName.Length - RemoveRight.Length, RemoveRight.Length).Remove(0, RemoveLeft.Length);
                if( int.TryParse(stripped,out int current) )
                {
                    if (current > maxTempNdx)
                        maxTempNdx = current;
                }
            }
            maxTempNdx++;
            fileName = RemoveLeft + maxTempNdx.ToString(numberSpecifier) + RemoveRight;
            File.CreateText(fileName); // optional
            return fileName;
        }
    
    0 讨论(0)
  • 2020-11-28 02:05

    I think you should try this:

    string path = Path.GetRandomFileName();
    path = Path.Combine(@"c:\temp", path);
    path = Path.ChangeExtension(path, ".tmp");
    File.Create(path);
    

    It generates a unique filename and creates a file with that file name at a specified location.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

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

    This could be handy for you... It's to create a temp. folder and return it as a string in VB.NET.

    Easily convertible to C#:

    Public Function GetTempDirectory() As String
        Dim mpath As String
        Do
            mpath = System.IO.Path.Combine(System.IO.Path.GetTempPath, System.IO.Path.GetRandomFileName)
        Loop While System.IO.Directory.Exists(mpath) Or System.IO.File.Exists(mpath)
        System.IO.Directory.CreateDirectory(mpath)
        Return mpath
    End Function
    
    0 讨论(0)
提交回复
热议问题