skip to Main Content

I am working with files on C# and I got to a point where I don’t know how to continue anymore.
The scenario is this: If I upload 3 or more files with the same name at the same time, I want to handle them and change their name to from "myfile.pdf" to "myfile.pdf(1)/(2)/(3)…" depending on how much files I upload.

This is what I have tried so far and in this case, this only works for only the second file because when the third one comes, it will check there is any file with the same – yes, okay name it "myfile.pdf(2) – but this exists too so it will go to another place.

How can I achieve having the same three files in the same folder with this naming convention?

Here’s what I have tried so far:

string FileName = "MyFile.pdf";
string path = @"C:ProjectMyPdfFiles"

            if (File.Exists(path))
            {
                int i = 1;
                var FileExists = false;
                while (FileExists==false)
                {
                    if (FileExists == false)
                    {
                      FileName = FileName + "(" + i + ")";
                    }
                    else
                        return;
                    i++;
                }
            }

And the result of this code is: "MyFile.pdf", "MyFile.pdf(1)" And the third one doesn’t load here.
I think I’m missing something in the loop or idk :(.
Can someone help me?

I have tried also this:

if(File.Exists(path) || File.Exists(path+"(")
//because when the second file its uploaded, its name will be SecondFile.pdf(1), so this will return true and will proceed running, but still the iteration will "always" start from 0 since everytime I upload a file, I have to refresh the process.

3

Answers


  1. This should do the job.

    public class Program
    {
    
        public static string GetUnusedFilePath(string directorypath, string filename, string ext)
        {
            string fullPath = $"{directorypath}{filename}{ext}";
            int inc = 0;
    
            // check until you have a filepath that doesn't exist
            while (File.Exists(fullPath))
            {
                fullPath = $"{directorypath}{filename}{inc}{ext}";
                inc++;
            }
    
            return fullPath;
        }
    
        public static void UploadFile(string filepath)
        {
            using (FileStream fs = File.Create(filepath))
            {
                // Add some text to file    
                Byte[] title = new UTF8Encoding(true).GetBytes("New Text File");
                fs.Write(title, 0, title.Length);
            }
        }
    
        public static void Main()
        {
            string[] filestoUpload = { "file", "file", "file", "anotherfile", "anotherfile", "anotherfile" };
            string directorypath = @"D:temp";
            string ext = ".txt";
    
            foreach(var file in filestoUpload)
            {
                var filePath = GetUnusedFilePath(directorypath, file, ext);
                UploadFile(filePath);
            }
    
    
        }
    
    }
    
    Login or Signup to reply.
  2. Don’t use return inside your while loop, better set ‘FileExists = true’ whenever you want you loop to stop. A return statement will exit your current method.

    I think your problem can be easily solved using recursion, something like this (untested):

    public class Program
    {
        public string FileName { get; set; }
        
        public Program() {
            string fileName = "MyFile.pdf";
            string path = @"C:ProjectMyPdfFiles";
            FileName = CheckFileName(path, fileName);
        }
        
        public string CheckFileName(string path, string fileName, int iteration = 0) {
            if (File.Exists($"{path}{fileName}")) {
                iteration++;
                CheckFileName(path, $"{fileName}({iteration})", iteration);
            }
            return fileName;
        }
    }
    

    What this does is: it CheckFileName method will keep calling itself until it finds a name that doesn’t exist yet.

    Login or Signup to reply.
  3. I solved this by creating new folders with special names using the code below:

    DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(FileDirectory);
    
                FileSystemInfo[] filesAndDirs = hdDirectoryInWhichToSearch.GetFileSystemInfos("*" + FullFileName + "*");
                int i = filesAndDirs.Length;
    
                if (i>1)
                {
                FileName = Filename + "(" + i ")";
        }
    

    So what this does is that it will count how many files we have in that folder with the same name, so I have to check if we have more than 1 file, then change it’s name to file(1).

    Thank you to everyone that tried to help me, much appreciated.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search