This extension handles things such as duplicate filenames and on-the-fly directory creation
Previously I showed how to
save multiple files of the same name
which I have used many times, so much in fact that I figured I would make a universal drop-in extension for it.
This new extension improves on the
SaveAs() method in a few ways:
- If a directory doesn't yet exist, it will be made
- If a file already exists with the same file name, an incremented tag will be added: abc.pdf, abc[1].pdf, abc[2].pdf, etc.
- It returns the name the file was saved with
There are two ways to call it:
- FileUploadControl.SaveAsNoOverwrite() :: will save to the current directory with the 'FileName' property of the 'FileUpload'
- FileUploadControl.SaveAsNoOverwrite(path) :: where 'path' is the path to save to
Here is the code:
public static string SaveAsNoOverwrite(this FileUpload up, string saveas)
{
string[] split = saveas.Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);
string directory = string.Empty;
for (int i = 0; i < split.Length - 1; i++) directory += split[i] + "\\";
string filename = split[split.Length - 1];
//saves to current directory if only filename is specified
if (string.IsNullOrEmpty(directory)) directory = HttpContext.Current.Server.MapPath(".") + "\\";
//creates directory if it does not exist
else if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
string[] fileNameSplit = filename.Split(new char[] { '.' });
string ext = "." + fileNameSplit[fileNameSplit.Count() - 1];
string prefix = filename.Substring(0, filename.Length - ext.Length);
int count = 1;
// if the files already exists, this will append a [x] where x is 0+(number of files existing with the same name)
while (File.Exists(directory + filename))
{
filename = prefix + "[" + count.ToString() + "]" + ext;
count++;
}
up.SaveAs(directory + filename);
return filename;
}
public static string SaveAsNoOverwrite(this FileUpload up)
{
return up.SaveAsNoOverwrite(up.FileName);
}