好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

dy("nrwz");

查看更多关于C# 输出字符串到文本文件中的实现代码的详细内容...

  阅读:49次