C#: How would you make a unique filename by adding a number?

前端 未结 18 776
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 11:46

I would like to create a method which takes either a filename as a string or a FileInfo and adds an incremented number to the filename if the file

18条回答
  •  遥遥无期
    2020-11-27 12:21

    I did it like this:

    for (int i = 0; i <= 500; i++) //I suppose the number of files will not pass 500
            {       //Checks if C:\log\log+TheNumberOfTheFile+.txt exists...
                if (System.IO.File.Exists(@"C:\log\log"+conta_logs+".txt"))
                {
                    conta_logs++;//If exists, then increment the counter
                }
                else
                {              //If not, then the file is created
                    var file = System.IO.File.Create(@"C:\log\log" + conta_logs + ".txt");
                    break; //When the file is created we LEAVE the *for* loop
                }
            }
    

    I think this version is not so hard like the others, and It's a straightforward answer for what the user wanted.

提交回复
热议问题