• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
张纯睿
博客园    首页    新随笔    联系   管理    订阅  订阅

C#学习笔记(22)——C#创建文本文件txt并追加写入数据

ref: https://www.cnblogs.com/Jacklovely/p/7263844.html

说明(2017-7-31 16:25:06):

1. 有两种办法,第一种是用FileStream创建txt,用StreamWriter写入数据,期间还要加上判断,是否存在这个txt文件,如果不存在就创建,存在就追加写入。太麻烦了!

2. 第二种是直接File.AppendAllText(string path, string contents);第一个参数是txt路径+文件名,第二个参数是写入内容。这个方法会自己判断文件是否存在,直接一步到位

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows;

namespace PPTtoJPG
{
    public class MyLog
    {
        public void ShowLog(string log)
        {
            //第一种方法,太麻烦了
            //StreamWriter sw = null;
            //if (!File.Exists("log.txt"))
            //{
            //    FileStream fs = new FileStream("log.txt", FileMode.Create, FileAccess.Write);
            //    sw = new StreamWriter(fs);
            //    sw.WriteLine(log);
            //    //记得要关闭!不然里面没有字!
            //    sw.Close();
            //    fs.Close();
            //}
            //else
            //{
            //    sw = File.AppendText("log.txt");
            //    sw.WriteLine(log);
            //    sw.Close();
            //    //MessageBox.Show("已经有log文件了!");
            //}

            //第二种方法,比较简单
            //\r\n要加在前面才会换行!
            File.AppendAllText("log.txt", "\r\n"+log);
        }
    }
}

 

posted @ 2021-06-30 10:46  张纯睿  阅读(3809)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3