public bool JournalFile(string journaljson)
{
string nowTime = DateTime.Now.ToString("yyyyMMdd");
string write_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
//string now = DateTime.Now.ToString();
string fileName = nowTime + ".txt";//名称
string content = write_time + " " + journaljson;//内容
var filePath = Path.Combine("log/", fileName);//路径
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", filePath);
try
{
if (!System.IO.File.Exists(path))
{
FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);//创建写入文件
System.IO.File.SetAttributes(path, FileAttributes.ReadOnly); //设置文件属性为只读
StreamWriter sw = new StreamWriter(fs1, Encoding.GetEncoding("utf-8"));
//sw.WriteLine(journaljson);//开始写入值
sw.WriteLine(content);//开始写入值
sw.Close();
fs1.Close();
}
else
{
new FileInfo(path).Attributes = FileAttributes.Normal;//获取文件的属性进行修改在操作
FileStream fs1 = new FileStream(path, FileMode.Append, FileAccess.Write);//打开文件
StreamWriter sw = new StreamWriter(fs1, Encoding.GetEncoding("utf-8"));
//sw.WriteLine(journaljson);//开始写入值
sw.WriteLine(content);//开始写入值
sw.Close();
fs1.Close();
}
}
catch (System.Exception ex)
{
return false;
}
return true;
}
该代码本人是用于写入日志文件,然后存在一个问题是直接打开txt文件查看没问题,但是如果通过服务器路径在网页上打开中文则会乱码,该问题没有找到解决方法,如有大神看到知道该问题麻烦指导告知;所以此处把从网页打开txt文件换成了直接下载txt文件到本地查看
ps:该文章为日常工作代码片段记录,如有涉及版权请告知