c#中对文件的操作
对文件操作时首先要导入System.IO 这个命名空间
以下操作都是在这个命名空间的基础上进行的
1.文件的读入
//path 为文件的路径 这个方法是对文件所有的行进行读取返回一个字符串数组类型的值文件的每一行为一项
string[] strList = File.ReadAllLines(path);//有多个重载 可以指定编码形式
//如果想读取有汉字的文本可以写为
string[] strList = File.ReadAllLines(path, Encoding.Default);
File.ReadLines(path);//读取文件的行 返回一个IEnumerable<string>类型的
File.ReadAllText(path);//读取文本所有内容并返回一个string类型的
2.写入数据
File.WriteAllLines(path,string[] contents)//重写所有的行 如果要重写有汉字的文本 方法如上 加一个Encoding.Default参数
//追加一行在文件的末尾
StreamWriter sw = new StreamWriter(path,true, Encoding.Default);
sw.WriteLine(stdList);
sw.Close();
3.清空文件
//path为路径
FileStream fs = new FileStream(path, FileMode.Truncate, FileAccess.ReadWrite);
fs.Close();

被折叠的 条评论
为什么被折叠?



