C# 把指定内容写入txt,如果txt已存在,则在txt添加内容

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:该文章为日常工作代码片段记录,如有涉及版权请告知

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值