如果条件满足一半,C# 阻止创建文件
C# prevent creating file if condition meet half-way
请问有没有什么方法可以防止在满足条件的情况下中途创建文件,使用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";
}
上面的代码仍然写入内容为"line 1"的"test.txt"文件。
如何让它不创建 "test.txt" 文件?
将您的输出保存到一个临时文件中。如果该过程完成,将该文件复制到您希望永久文件所在的位置。如果没有,只需 return,下次 Windows 对临时文件夹进行清理时,该文件将被删除。
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";
}
请问有没有什么方法可以防止在满足条件的情况下中途创建文件,使用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";
}
上面的代码仍然写入内容为"line 1"的"test.txt"文件。
如何让它不创建 "test.txt" 文件?
将您的输出保存到一个临时文件中。如果该过程完成,将该文件复制到您希望永久文件所在的位置。如果没有,只需 return,下次 Windows 对临时文件夹进行清理时,该文件将被删除。
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";
}