Automatically rename a file if it already exists in Windows way

前端 未结 10 633
谎友^
谎友^ 2020-11-28 06:50

My C# code is generating several text files based on input and saving those in a folder. Also, I am assuming that the name of the text file will be same as input.(The input

10条回答
  •  自闭症患者
    2020-11-28 07:05

    This will check for the existence of files with tempFileName and increment the number by one until it finds a name that does not exist in the directory.

    int count = 1;
    
    string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
    string extension = Path.GetExtension(fullPath);
    string path = Path.GetDirectoryName(fullPath);
    string newFullPath = fullPath;
    
    while(File.Exists(newFullPath)) 
    {
        string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
        newFullPath = Path.Combine(path, tempFileName + extension);
    }
    

提交回复
热议问题