下面給大家分享一小段代碼給大家介紹C# 輸出字符串到文本文件中,具體代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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在文件末尾添加數(shù)據(jù) tw.WriteLine($ "----產(chǎn)生時(shí)間:{DateTime.Now:yyyy-MM-dd HH:mm:ss}---------------------------------------------------------------------" ); tw.WriteLine(data.ToJsonStr()); tw.Close(); } catch (Exception e) { } } } public static class Json { /// <summary> /// 轉(zhuǎn)成json字符串 /// </summary> public static string ToJsonStr( this object obj) { return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); } } |
總結(jié)
以上所述是小編給大家介紹的C# 輸出字符串到文本文件中的實(shí)現(xiàn)代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://www.cnblogs.com/dawenyang/archive/2018/05/29/9103509.html