zoukankan      html  css  js  c++  java
  • C#学习笔记(22)——C#创建文本文件txt并追加写入数据

    说明(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文件了!");
                //}
    
                //第二种方法,比较简单
                //
    要加在前面才会换行!
                File.AppendAllText("log.txt", "
    "+log);
            }
        }
    }
  • 相关阅读:
    Python学习之路2☞数据类型与变量
    Python学习之路1☞简介及入门代码
    OpenStack组件系列☞horizon搭建
    39
    38
    37
    36
    35
    33
    32
  • 原文地址:https://www.cnblogs.com/Jacklovely/p/7263844.html
Copyright © 2011-2022 走看看