C# 输出字符串到文本文件中

时间:2023-03-09 04:30:17
C# 输出字符串到文本文件中

写个博客记录下,方便以后使用:

    public class WriteHelper
{
public static void WriteFile(object data)
{
try
{
string path = $@"D:\TokenLog\day{DateTime.Now:yyyy-MM-dd}";
var filename = $"TokenLog{DateTime.Now:yyyy-MM-dd HH}.txt";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
TextWriter tw = new StreamWriter(Path.Combine(path, filename), true); //true在文件末尾添加数据 tw.WriteLine($"----产生时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}---------------------------------------------------------------------"); tw.WriteLine(data.ToJsonStr());
tw.Close();
}
catch (Exception e)
{ }
}
}
public static class Json
{
/// <summary>
/// 转成json字符串
/// </summary>
public static string ToJsonStr(this object obj)
{
return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
} }