Thursday, August 26, 2010

How to save a file with number prefix while uploading if file being saved previously

This will save, say you upload Image.gif.
  1. First save of Image.gif will be Image001.gif
  2. Then again if you try to save Image.gif, Then it will be Image002.gif
  3. And so on...
FileInfo file = new FileInfo(this.fileImage.PostedFile.FileName);
string filePreFix = file.Name.Replace(file.Extension, string.Empty).ToLower();
string fileExtension = file.Extension;
int maxFile = 0;
foreach (FileInfo f in new DirectoryInfo(Server.MapPath("~/Images")).GetFiles())
{
    string name = f.Name.ToLower();
    if (name.Contains(filePreFix) && f.Extension.ToLower().Equals(fileExtension))
    {
        int number = int.Parse(name.Replace(filePreFix, string.Empty).Replace(fileExtension, string.Empty));
        if (number > maxFile) maxFile = number;
    }
}
string newFileName = string.Format("{0}{1:000}{2}", filePreFix, maxFile + 1, fileExtension);

2 comments:

Anonymous said...

Thanks Charith, I used this in my application

Rama

Charith Shyam Gunasekara said...

You are welcome

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...