Automatically rename a file if it already exists in Windows way

前端 未结 10 650
谎友^
谎友^ 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:03

    You can declare a Dictionary to keep the number of times each root file name was saved. After that, on your Save method, just increase the counter and append it to the base file name:

    var key = fileName.ToLower();
    string newFileName;
    if(!_dictionary.ContainsKey(key))
    {
        newFileName = fileName;
        _dictionary.Add(key,0);
    }
    else
    {
        _dictionary[key]++;
       newFileName = String.Format("{0}({1})", fileName, _dictionary[key])
    }
    

    This way, you'll have a counter for each distinct file name: AAA(1), AAA(2); BBB(1)...

提交回复
热议问题