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

后端 未结 17 2096
北恋
北恋 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条回答
  •  旧时难觅i
    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;
        }
    

提交回复
热议问题