Search code examples
c#asp.netfilesystems

Generate a filename with a number inside parentheses


I'm working with ASP.NET project where the user can upload files to the server. I want to save the file with its original name, but if the 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 the same name already 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 a regex over DirectoryInfo.EnumerateFiles(), but is that a good approach?


Solution

  • 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.
        }
    }