Automatically rename a file if it already exists in Windows way

前端 未结 10 649
谎友^
谎友^ 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 06:52

    How about just:

    int count = 1;
    String tempFileName = newFileName;
    
    foreach (var item in allFiles)
    {
      if (tempFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase))
      {
        tempFileName = String.Format("{0}({1})", newFileName, count++);
      }
    }
    

    This will use the original file name if it's not there, if not it'll take a new file name with the index in brackets (although this code isn't taking the extension into account). If the newly generated name "text(001)" is used then it'll increment until it finds a valid unused file name.

提交回复
热议问题