IO文本操作

时间:2023-03-09 02:13:35
IO文本操作

创建文件并写入内容

StreamWriter sw = new StreamWriter(url, “false 覆盖,true 追加”, Encoding.UTF8);
sw.Write(“内容”);
sw.Close();

读取文件内容

FileInfo info = new FileInfo("路径");
FileStream fs = new FileStream(pash, FileMode.OpenOrCreate, FileAccess.Read);
byte[] b = new byte[info.Length];
fs.Read(b, ,b.Length);
UTF8Encoding utf = new UTF8Encoding();
string st = utf.GetString(b);
fs.Close();
//st 文本内容

FileStream 个方法中也有创建、写入、读取等方法。

补充:

是否存在,没有新建

if (!File.Exists(file))
{
FileStream fs1 = new FileStream(file, FileMode.Create, FileAccess.Write);//创建写入文件
fs1.Close();
}

一行一行的读取

string text = System.IO.File.ReadAllText(file);
Console.WriteLine(text);
//从头到尾以流的方式读出文本文件
//该方法会一行一行读出文本
using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
{
string str;
while ((str = sr.ReadLine()) != null)
{
Console.WriteLine(str);
}
}
Console.Read();

清空

System.IO.File.WriteAllText(file, string.Empty);