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

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...