本文通过一个简单的代码给大家介绍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# 输出字符串到文本文件中的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程学习网网站的支持!