4

I want counter with 5 digits, for exaple: 00000, 00001, 00002.... I creating files with this command:

FileStream Fl = File.Create(@"C:\\U\\L\\Desktop\\" + "i" + (counter) + ".xml");

Definition of counter:

int counter;

My increment: counter++;

Have you any idea, how i could make 5 digits counter? Thanks for all ideas:)

Kate
  • 372
  • 2
  • 11
  • 24

7 Answers7

15

About custom numeric format strings

int value = 123;
Console.WriteLine(value.ToString("00000"));
// Displays 00123 
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
4

Do you mean something like this:

  counter.ToString().PadLeft(5, '0')
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    In general you should not use `PadLeft()` because it doesn't work with negative numbers. It's fine for the OP's requirement and it seems very unlikely you'd ever need to pad negative numbers with leading zeroes, but worth pointing this out methinks. – Matthew Watson Aug 29 '13 at 08:17
4

You can use a standard formatting string:

... + counter.ToString("D5") + ...

Or with Format method:

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

With the string interpolation of C# 6.0 (Visual Studio 2015) and later, that will be:

$"... {counter:D5} ..."
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
2

You just need to use the appropriate format specification when converting the counter to a string.

Try this:

string counterString = counter.ToString("00000");

Or (equivalent):

string counterString = counter.ToString("d5");
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

You can use PadLeft with String.Format. Note that you should use Path.Combine if you build paths.

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);
    // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

this should do it

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

or

asString = string.Format("{0:00000}", counter);

output will be 00005

Ehsan
  • 31,833
  • 6
  • 56
  • 65
0

You can use the ToString function:

counter.ToString("00000");
fhr
  • 1