Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 5位计数器_C#_Filenames_Counter_Auto Increment - Fatal编程技术网

C# 5位计数器

C# 5位计数器,c#,filenames,counter,auto-increment,C#,Filenames,Counter,Auto Increment,我想要5位数的计数器,例如:000000000100002。。。。 我使用以下命令创建文件: FileStream Fl = File.Create(@"C:\\U\\L\\Desktop\\" + "i" + (counter) + ".xml"); 计数器的定义: int counter; 我的增量: 计数器+++ 你知道吗,我怎么做5位数的计数器?谢谢你的建议:)关于 将计数器转换为字符串时,只需使用适当的格式规范 试试这个: string counterString = counte

我想要5位数的计数器,例如:000000000100002。。。。 我使用以下命令创建文件:

FileStream Fl = File.Create(@"C:\\U\\L\\Desktop\\" + "i" + (counter) + ".xml");
计数器的定义:

int counter;
我的增量:
计数器+++

你知道吗,我怎么做5位数的计数器?谢谢你的建议:)

关于


将计数器转换为字符串时,只需使用适当的格式规范

试试这个:

string counterString = counter.ToString("00000");
或(同等):


你的意思是这样的:

  counter.ToString().PadLeft(5, '0')
这应该可以

int counter = 5;
string asString = counter.ToString("D5");


输出将为
00005

您可以使用标准格式字符串:

... + counter.ToString("D5") + ...
或使用
格式
方法:

string.Format("... {0:D5} ...", counter)

随着C#6.0(Visual Studio 2015)及更高版本的发布,这将是:

$"... {counter:D5} ..."

您可以将
PadLeft
String.Format
一起使用。请注意,如果构建路径,应使用
Path.combined

int counter = 0;
for (int i = 0; i < 1000; i++)
{
    string counterText = (counter++).ToString().PadLeft(5, '0');
    string fileName = string.Format("i{0}.xml", counterText);
    string fullName = Path.Combine(@"C:\U\L\Desktop\", fileName);
    FileStream Fl = File.Create(fullName);
    // ...
}
int计数器=0;
对于(int i=0;i<1000;i++)
{
字符串counterText=(counter++).ToString().PadLeft(5,'0');
字符串文件名=string.Format(“i{0}.xml”,counterText);
字符串fullName=Path.Combine(@“C:\U\L\Desktop\”,文件名);
FileStream Fl=File.Create(全名);
// ...
}

您可以使用ToString功能:

counter.ToString("00000");

counter.ToString(“00000”)看看这个,虽然我同意使用
Path.Combine
是一种方法,但这并不能真正回答问题……我认为您需要
{0:D5}
。@JeppeStigNielsen+Nolonar:谢谢。编辑我的答案,改为使用
PadLeft
。@JeppeStigNielsen:有几种方法。如果可以的话,我更喜欢
PadLeft
,因为它更显式。虽然
string.PadLeft()
适用于这个特定的示例,但对于负数它却失败得惊人。只是说,;)一般来说,您不应该使用
PadLeft()
,因为它不适用于负数。这符合OP的要求,而且似乎不太可能需要用前导零填充负数,但我认为值得指出这一点。
$"... {counter:D5} ..."
int counter = 0;
for (int i = 0; i < 1000; i++)
{
    string counterText = (counter++).ToString().PadLeft(5, '0');
    string fileName = string.Format("i{0}.xml", counterText);
    string fullName = Path.Combine(@"C:\U\L\Desktop\", fileName);
    FileStream Fl = File.Create(fullName);
    // ...
}
counter.ToString("00000");