C#读取文本文件
1 // 读操作 2 public static void Read() 3 { 4 // 读取文件的源路径及其读取流 5 string strReadFilePath = @"../../data/ReadLog.txt"; 6 StreamReader srReadFile = new StreamReader(strReadFilePath); 7 8 // 读取流直至文件末尾结束 9 while (!srReadFile.EndOfStream)10 {11 string strReadLine = srReadFile.ReadLine(); //读取每行数据12 Console.WriteLine(strReadLine); //屏幕打印每行数据13 }14 15 // 关闭读取流文件16 srReadFile.Close();17 Console.ReadKey();18 }
C# 写文本文件
1 // 写操作 2 public static void Write() 3 { 4 // 统计写入(读取的行数) 5 int WriteRows = 0; 6 7 // 读取文件的源路径及其读取流 8 string strReadFilePath = @"../../data/ReadLog.txt"; 9 StreamReader srReadFile = new StreamReader(strReadFilePath);10 11 // 写入文件的源路径及其写入流12 string strWriteFilePath = @"../../data/WriteLog.txt";13 StreamWriter swWriteFile = File.CreateText(strWriteFilePath);14 15 // 读取流直至文件末尾结束,并逐行写入另一文件内16 while (!srReadFile.EndOfStream)17 {18 string strReadLine = srReadFile.ReadLine(); //读取每行数据19 ++WriteRows; //统计写入(读取)的数据行数20 21 swWriteFile.WriteLine(strReadLine); //写入读取的每行数据22 Console.WriteLine("正在写入... " + strReadLine);23 }24 25 // 关闭流文件26 srReadFile.Close();27 swWriteFile.Close();28 29 Console.WriteLine("共计写入记录总数:" + WriteRows);30 Console.ReadKey();31 }
完整源代码
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 using System.IO; //引用输入输出操作的命名空间 6 7 namespace ReadWriteFile 8 { 9 class Program10 {11 12 //主函数13 static void Main(string[] args)14 {15 Read(); //读操作16 Write(); //写操作17 18 }19 20 //读操作21 public static void Read()22 { 23 //读取文件的源路径及其读取流24 string strReadFilePath = @"../../data/ReadLog.txt";25 StreamReader srReadFile = new StreamReader(strReadFilePath);26 27 //读取流至文件末尾结束28 while(!srReadFile.EndOfStream)29 {30 string strReadLine = srReadFile.ReadLine(); //读取每行数据31 Console.WriteLine(strReadLine); //屏幕打印每行数据32 }33 34 //关闭读取流文件35 srReadFile.Close();36 Console.ReadKey();37 38 }39 40 //写操作41 public static void Write()42 { 43 //统计写入(读取的行数)44 int WriteRows = 0;45 46 //读取文件的源路径及其读取流47 string strReadFilePath = @"../../data/ReadLog.txt";48 StreamReader srReadFile = new StreamReader(strReadFilePath);49 50 //写入文件的源路径及其写入流51 string strWriteFilePath = @"../../data/WriteLog.txt";52 StreamWriter swWriteFile = File.CreateText(strWriteFilePath);53 54 //读取流至文件末尾结束,并逐行写入另一文件内55 while(!srReadFile.EndOfStream)56 {57 string strReadLine = srReadFile.ReadLine(); //读取每行数据58 ++WriteRows; //统计写入(读取)的数据行数59 60 swWriteFile.WriteLine(strReadLine); //写入读取的每行数据61 Console.WriteLine("正在写入..."+strReadLine);62 }63 64 //关闭流文件65 srReadFile.Close();66 swWriteFile.Close();67 68 Console.WriteLine("共计写入记录总数:"+WriteRows);69 Console.ReadKey();70 }71 72 }73 }
参考链接:https://blog.csdn.net/hongkaihua1987/article/details/80432436