Reputation: 53
I wish to keep three digits for the variable in a for loop. E.g.
for (int i = 002; i <= 033; i++)
{
string localFilename = @"\\psf\Home\Pictures\Maulavi\" + i + ".jpg";
using (WebClient client = new WebClient())
{
MessageBox.Show(i.ToString());
client.DownloadFile("http://eap.bl.uk/EAPDigitalItems/EAP566/EAP566_1_1_19_2-EAP566_Maulvi_January_1946_v43_no2_" + i + "_L.jpg", localFilename);
}
}
However I changes to being just 2
and 3
etc. I want it to stay as 002
and 003
etc. How do I do that?
Upvotes: 1
Views: 98
Reputation: 166
Use like following it's works as you want:
char padChar = '0';
for (int i = 002; i <= 033; i++)
{
string localFilename = @"\\psf\Home\Pictures\Maulavi\" + i + ".jpg";
string padStr = i.ToString().PadLeft(3,padChar);
using (WebClient client = new WebClient())
{
MessageBox.Show(i.ToString());
client.DownloadFile("http://eap.bl.uk/EAPDigitalItems/EAP566/EAP566_1_1_19_2-EAP566_Maulvi_January_1946_v43_no2_" + padStr + "_L.jpg", localFilename);
}
}
For more about this visit: http://mahedee.net/padding-character-with-string/
Upvotes: 0
Reputation: 39085
You can do i.ToString("D3")
or i.ToString("000")
.
For more information on number to string conversions, have a look at Standard Numeric Format Strings.
Upvotes: 1
Reputation: 237
Use string.Format(@"\psf\Home\Pictures\Maulavi{0:000}.jpg", i)
Format will also have better performance than string concatenation.
Upvotes: 0
Reputation: 35780
Format string with overload of function ToString()
:
for(int i = 2; i <= 33; i++)
{
string localFilename = @"\\psf\Home\Pictures\Maulavi\" + i.ToString("000") + ".jpg";
}
Or you can use Format
function:
String.Format("{0:000}", i);
Upvotes: 0
Reputation: 39956
Try ToString("000")
like this:
for (int i = 002; i <= 033; i++)
{
....
....
MessageBox.Show(i.ToString("000")); // 002 , 003 , ...
}
Upvotes: 2