Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过创建更多文件写入文件(而不是替换/覆盖)_C#_File_Streamwriter - Fatal编程技术网

C# 通过创建更多文件写入文件(而不是替换/覆盖)

C# 通过创建更多文件写入文件(而不是替换/覆盖),c#,file,streamwriter,C#,File,Streamwriter,是否有任何方法可以修改以下简单代码,以便一旦创建了文件myBackup.csv,并且代码被反复运行,它不仅会重新写入同一个文件并销毁以前的内容,还会创建更多的文件 string localPath = somePath + Path.DirectorySeparatorChar + "myBackup.csv"; StreamWriter sw = new StreamWriter( localPath ); sw.WriteLine( "blah blah:" ); foreach ( var

是否有任何方法可以修改以下简单代码,以便一旦创建了文件
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

你完全正确。我的错误。我会立即编辑标题。我想要更多的文件,而不是在以前的内容上写得太多。谢谢你指出这一点。。。