I'm working with asp.net project where user can upload files to server. I want to save the file with its original name, but if file with the same name already exists How can I generate a filename with a number in the parenthesis like windows does?
Files are uploaded to a particular folder and saved with its client side name itself. So, If a file named myimage.jpg is uploaded and a file with same name a开发者_如何学编程lready exists in the server, I need to rename it to myimage(1).jpg or if 'myimage.jpg' to 'myimage(n).jpg' exists, I need to rename it to myimage(n+1).jpg.
What will be the best way to search for and generate such file names? My first guess was to use linq with regex over DirectoryInfo.EnumerateFiles()
, but is that a good approach?
If the files with same orginal name don't have to be shown sorted by upload date/time, you could simply append System.Guid.NewGuid().ToString() to the file name.
public static object lockObject = new object();
void UploadFile(...)
{
//-- other code
lock (lockObject)
{
int i = 1;
string saveFileAs = "MyFile.txt";
while (File.Exists(saveFileAs))
{
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(saveFileAs);
string ext = Path.GetExtension(saveFileAs)
saveFileAs = String.Concat(fileNameWithoutExt, "(", i.ToString(), ")", ext);
i++;
}
//-- Now you can save the file.
}
}
You don't need LINQ or regex.
If the original filename exists, append (1)
to the name.
If that exists, append (2)
to the (original) name.
And so on...
精彩评论