将 Environment.NewLine 添加到文件流中



我正在 .net 控制台应用程序中制作一个不和谐的机器人,我在流编写器上挣扎了很多时间,所以我正在尝试文件流,我没有遇到与流编写器相同的错误,但我在添加新行时遇到了问题,

string path = @"C:PathWouldBeHereLog.txt"; // path to file
using (FileStream fs = File.Create(path))
{
    string dataasstring = $"[{DateTime.Now.Hour}:{DateTime.Now.Minute}][Log]{Context.User.Username}:  {Context.Message.Content}"; //your data
    byte[] info = new UTF8Encoding(true).GetBytes(dataasstring);
    fs.Write(info, 0, info.Length);
}

现在我知道我可以使用Environment.NewLine,但我是一个完全的菜鸟,不知道我应该把它放在代码中的什么位置。我知道它有点问,但如果有人可以调整我的代码,而不是记录一件事(删除以前的日志(,而是添加一个换行符。

您正在使用 File.Create ,它会在该位置创建一个新文件并删除该位置已存在的任何文件。相反,您想要的是使用带有 FileMode.Append 标志的 FileStream 构造函数:

using (FileStream fs = new FileStream(path, FileMode.Append))
{
    string dataasstring = $"[{DateTime.Now.Hour}:{DateTime.Now.Minute}][Log]{Context.User.Username}:  {Context.Message.Content}{Environment.NewLine}"; //your data
    byte[] info = new UTF8Encoding(true).GetBytes(dataasstring);
    fs.Write(info, 0, info.Length);
}

或者,您可以完全跳过流方法,只使用以下方法:

string dataasstring = $"[{DateTime.Now.Hour}:{DateTime.Now.Minute}][Log]{Context.User.Username}:  {Context.Message.Content}{Environment.NewLine}";
File.AppendAllText(path, dataasstring);

最新更新