通过创建更多文件写入文件(而不是 replacing/overwriting)

Writing to file by creating further files (and not replacing/overwriting)

有没有什么办法可以修改下面的简单代码,让文件myBackup.csv一旦创建,代码一遍又一遍运行,不只是重写同一个文件并销毁以前的内容,但创建更多文件?

string localPath = somePath + Path.DirectorySeparatorChar + "myBackup.csv";
StreamWriter sw = new StreamWriter( localPath );
sw.WriteLine( "blah blah:" );
foreach ( var element in entryId )
    sw.WriteLine( element );
localSaver.Close();

所以你想检查文件是否存在,如果文件存在则选择另一个文件名?

string localPath = somePath + Path.DirectorySeparatorChar + "myBackup.csv";

int counter = 1;
while (File.Exists(localPath))
{
    localPath = somePath + Path.DirectorySeparatorChar + "myBackup-" + counter + ".csv";

    counter++;
}

然后在 StreamWriter 构造函数中使用 localPath