Reputation:
Is there any way to modify the following simple code, so that once the file myBackup.csv
is created and the code is run over and over again, it doesn't just re-write the same file and destroy the previous contents, but creates further files?
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();
Upvotes: 1
Views: 42
Reputation: 156918
So you want to check if the file exists and choose another file name if the file exists?
string localPath = somePath + Path.DirectorySeparatorChar + "myBackup.csv";
int counter = 1;
while (File.Exists(localPath))
{
localPath = somePath + Path.DirectorySeparatorChar + "myBackup-" + counter + ".csv";
counter++;
}
Then use localPath
in your StreamWriter
constructor.
Upvotes: 3