c#文件命名增量名称

本文关键字:文件 | 更新日期: 2023-09-27 17:50:28

我正在使用c#创建一个小应用程序。我需要以递归的方式命名文件,在创建文件名时增加文件名。我需要以下格式的文件名:"alt-001.tmp"alt-002.tmp"等等。我总是看到00在增加的数字之前被删除,因此,例如,001++然后返回2而不是002。

谢谢你的帮助,如果这听起来像一个愚蠢的问题,我很抱歉。

c#文件命名增量名称

用于将数字格式化为字符串:

fileName = string.format("alt-{0:000}.tmp", yourCounterVariable);

字符串格式命令,用那里的变量替换"{0}"。然后列后的值是一个掩码,说明该替换应该如何格式化。

您需要在计数器上使用ToString()并使用格式字符串。

var a = 0;
(a++).ToString("000").Dump();
(a++).ToString("000").Dump();

输出为3位。

结果:001002

像下面这个例子?

int unique = 0;
string destPath = string.Format("alt-{0:000}.tmp", unique);
while (File.Exists(destPath))
{
     unique++;
     destPath = Path.Combine(easyPath, string.Concat(baseName, " ", unique.ToString("00", CultureInfo.InvariantCulture), file.Extension));
}