Showing posts with label File Handling. Show all posts
Showing posts with label File Handling. Show all posts

Monday, April 18, 2011

rename file if already exists in database while uploading

I like to use the the way windows allows for unique file or folders: New Folder --> New Folder (2) if the folder exists.
string fileName = /* your file path */
string newFileName = fileName;
int count = 2;
while (System.IO.File.Exists(newFileName))
{
    if(fileName.EndsWith("\\")) fileName = fileName.Remove(fileName.Length-1);

    string dir = fileName.Substring(0,fileName.LastIndexOf("\\"));
    string fName = fileName.Replace(dir, "");
    string name = fName.Split('.')[0];
    string ext = fName.Split('.')[1];
    newFileName = dir + string.Format("{0} ({1}).{2}", name, count.ToString(), ext);
    count++;
}
// Here you would use your unique newFileName
I hope I understood you correctly