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文件了!");
//} //第二种方法,比较简单
//\r\n要加在前面才会换行!
File.AppendAllText("log.txt", "\r\n"+log);
}
}
}
上一篇:SQL Server主从配置,端口开放以及服务器改名后的影响


下一篇:C#——图片操作类简单封装