软件编程
位置:首页>> 软件编程>> C#编程>> C# 输出字符串到文本文件中的实现代码

C# 输出字符串到文本文件中的实现代码

作者:大稳·杨  发布时间:2022-08-25 11:18:13 

标签: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
{
   /// <summary>
   /// 转成json字符串
   /// </summary>
   public static string ToJsonStr(this object obj)
   {
     return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
   }
}

总结

以上所述是小编给大家介绍的C# 输出字符串到文本文件中的实现代码网站的支持!

来源:https://www.cnblogs.com/dawenyang/archive/2018/05/29/9103509.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com