Saving multiple files of the same name (C#)

Save multiple files of the same name without overwriting anything

I am sure I am not the only one to run into the problem of saving files with the FileUpload control.  The problem with this can be if a user has already uploaded a file someFile.txt and they are trying to upload another file someFile.txt.  Normally, you have 2 options:

  • Delete the old file and save the new one
  • Inform the user there is already a file there under that name


Recently, one of these options just wouldn't cut it, so I borrowed an idea from Microsoft Windows: if you save two identical files on your desktop, it simply changes the filename slightly.   For example, if there is already someFile.txt on my desktop, and I try to paste a file with the same name, Windows will just rename it Copy of someFile.txt and if I paste again, it will be named Copy (2) of someFile.txt.  Now that is a decent idea, but I hate the 'Copy of' part of the name, so I decided to make that part a little better.

 

What this snippet does, is take in the FileUpload control you are saving from and saves it to the directory you specify (saveTo).  It will first try to save the file as someFile.txt, but if that is already there, it will save as someFile[1].txt and if that is there it will save as someFile[2].txt and so on.  This is very handy if you need to keep mulitple versions of one file.  It return a FileInfo object so you can get the name it saved as, file size, etc..

 

[code:c#]

public static FileInfo saveFileWithoutOverwrite(FileUpload fu, string saveTo)
{
    int count = 1;
    string fileName = fu.FileName;
    string[] fileNameSplit = fileName.Split(new char[] { '.' });
    string ext = "." + fileNameSplit[fileNameSplit.Count() - 1];
    string prefix = fileName.Substring(0, fileName.Length - ext.Length);
    while (File.Exists(saveTo+ fileName))
    {
        fileName = prefix + "[" + count.ToString() + "]" + ext;
        count++;
    }
    fu.SaveAs(saveTo + fileName);
    return new FileInfo(saveTo + fileName);
}

[/code]

 

This has proved to be very useful in developing a Trouble Ticket System, where files are often updated and saved, but we do not want to lose the older records. This could be easily modified to take a Stream input and save it as well if you are not working directly with a FileUpload control.

Comments (3) -

  • Excellent tip.  I believe BlogEngine currently suffers from an issue where a duplicate upload will overwrite an existing file.  Perhaps this could be useful to solve this issue.
Comments are closed