栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

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

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/954486.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号