我有一个足够简单的类,用于将文本记录到.txt文件中我遇到的问题是,如果文本文件不存在,我将在代码中显示的点处获得异常.程序崩溃后,文本文件出现在文件夹中.如果我在log.txt文件存在的情况下运行该程序,它可以完美地运行.
代码:
class logger
{
public string source;
//public logger()
//{
//}
public logger(string source)
{
CheckExists(source);
this.source = source + "log.txt";
}
private void CheckExists(string source)
{
if (!File.Exists(source + "log.txt"))
{
File.Create(source + "log.txt");
}
}
public void WriteToLog(string output)
{
try
{
using (StreamWriter sw = File.AppendText(this.source))
{
sw.WriteLine(output);
sw.Close();
}
}
catch (Exception e)
{
//point at which the code breaks;
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
你为什么不使用File.AppendAllText
File.AppendAllText(this.source, output);
Run Code Online (Sandbox Code Playgroud)