1.写入文件
1 2 3 4 5 6 7 | using (FileStream fileStream = File.Create(fileName)) //打开文件流 (创建文件并写入) { string name = "12345567778890" ; byte [] bytes = Encoding.Default.GetBytes(name); fileStream.Write(bytes, 0, bytes.Length); fileStream.Flush(); } |
1 2 3 4 5 6 | using (FileStream fileStream = File.Create(fileName)) //打开文件流 (创建文件并写入) { StreamWriter sw = new StreamWriter(fileStream); sw.WriteLine( "1234567890" ); sw.Flush(); } |
1 2 3 4 5 6 | using (StreamWriter sw = File.AppendText(fileName)) //流写入器(创建/打开文件并写入) { string msg = "今天是Course6IOSerialize,今天上课的人有55个人" ; sw.WriteLine(msg); sw.Flush(); } |
1 2 3 4 5 6 7 | 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.文件读取
1 2 3 4 5 6 7 | 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); |
3.大文件读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | using (FileStream stream = File.OpenRead(fileName)) //分批读取 { int length = 5; int result = 0; do { byte [] bytes = new byte [length]; result = stream.Read(bytes, 0, 5); for ( int i = 0; i < result; i++) { Console.WriteLine(bytes[i].ToString()); } } while (length == result); } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步