这是生成增量文件名的一种简单但有效的方法。它将直接查看当前(您可以轻松地将其指向其他地方)并搜索具有基本 YourApplicationName*.txt 的文件(同样您可以轻松更改它)。它将从 0000 开始,因此第一个文件名将是 YourApplicationName0000.txt。如果由于某种原因在左右部分(不是数字)之间存在带有垃圾的文件名,则这些文件将通过 tryparse 调用而被忽略。
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;
}