1.文件写入
string fileName = Path.Combine(LogPath, "log.txt"); Directory.CreateDirectory(LogPath);//创建了文件夹之后,才能创建里面的文件 using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入) { string name = "12345567778890"; byte[] bytes = Encoding.Default.GetBytes(name); fileStream.Write(bytes, 0, bytes.Length); fileStream.Flush(); } using (FileStream fileStream = File.Create(fileName))//打开文件流 (创建文件并写入) { StreamWriter sw = new StreamWriter(fileStream); sw.WriteLine("1234567890"); sw.Flush(); } using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入) { string msg = "15663353135"; sw.WriteLine(msg); sw.Flush(); } using (StreamWriter sw = File.AppendText(fileName))//流写入器(创建/打开文件并写入) { string name = "0987654321"; byte[] bytes = Encoding.Default.GetBytes(name); sw.BaseStream.Write(bytes, 0, bytes.Length); sw.Flush(); }
2.文件读取
foreach (string result in File.ReadAllLines(fileName))//逐行读取 { Console.WriteLine(result); }
string sResult = File.ReadAllText(fileName);//一次性读取所有内容,返回字符串
Byte[] byteContent = File.ReadAllBytes(fileName);//一次性读取所有内容,返回字节数组 string sResultByte = System.Text.Encoding.UTF8.GetString(byteContent);//将字节数组转为字符串
//如果一个文本文件太大,可以选择分批读取 using (FileStream stream = File.OpenRead(fileName))//分批读取 { int length = 5; int result = 0; do { byte[] bytes = new byte[length]; result = stream.Read(bytes, 0, length); for (int i = 0; i < result; i++) { Console.WriteLine(bytes[i].ToString()); } } while (length == result); }