您的当前位置:首页正文

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

来源:化拓教育网
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{

///

/// 转成json字符串 ///

public static string ToJsonStr(this object obj) {

return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); }}

因篇幅问题不能全部显示,请点此查看更多更全内容