I would like to ask is there anyway to prevent creating a file half-way if a condition is met, using StreamWriter:
public static string stopWriteFileHalfWay(string option)
{
string filePath = @"d:\test\test.txt";
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine("line 1");
return "after line 3"; // => exit and do not want to create and write any file
sw.WriteLine("line 2");
}
return "completed";
}
The above code still writes "test.txt" file with "line 1" in the content.
How can I make it not create "test.txt" file ?
Save your output to a temporary file. If the process completes, copy that file to the location you want the permanent file to be. If not, simply return, and the file will get deleted the next time Windows takes a cleaning pass at the temporary file folder.
public static string stopWriteFileHalfWay(string option)
{
string tempPath = Path.GetTempFileName();
using (StreamWriter sw = File.AppendText(tempPath))
{
sw.WriteLine("line 1");
return "after line 3"; // => exit and do not want to create and write any file
sw.WriteLine("line 2");
}
File.Move(tempPath, @"d:\test\test.txt");
return "completed";
}