如果是操作文本文件类型

推荐使用:  StreamReader、StreamWriter

示例:StreamWriter 用于写入,可以使用 WriteLine(xxx) 函数将内容写入指定文件当中

 1 try 2 { 3     //StreamWriter用于将内容写入文本文件中 4     //path: 要写入文件的路径 5     //append: true 将数据追加到该文件的末尾; false 覆盖该文件。 6     //Encoding.UTF8  写入的编码格式 7     //如果指定的文件不存在,构造函数将创建一个新文件。 8     using (StreamWriter sw = new StreamWriter(@"D:\aaa.txt", true, Encoding.UTF8)) 9     {10         sw.WriteLine("我是老大");11         sw.WriteLine("我是老三");12         sw.WriteLine("我是老四");13         sw.WriteLine("我是老五");14         sw.Close();15     }16     Console.WriteLine("写入成功了。。。");17 }18 catch (Exception ex)19 {20     Console.WriteLine(ex.Message);21 }

如果文件不存在,会自动创建。

IO文件读写操作_IO文件读写

 StreamReader  用于读取,ReadLine 表示一行行读取,还有其他读取方法,具体到程序集查看即可

 1 //StreamReader用法 2 try 3 { 4     using (StreamReader sr = new StreamReader(@"D:\aaa.txt", Encoding.UTF8)) 5     { 6         while (true) 7         { 8             var str = sr.ReadLine();  //一行行的读取 9             if (str == null)          //读到最后会返回null10             {11                 break;12             }13             Console.WriteLine(str);14         }15         sr.Close();16     }17     Console.WriteLine("读取结束了。。。");18 }19 catch (Exception ex)20 {21     Console.WriteLine(ex.Message);22 }

IO文件读写操作_IO文件读写_02

如果是操作 其他类型的文件(包括文本文件),可以使用 FileStream,

比如我们操作一张图片文件

 1 //FileStream 用法  读取文件 2 try 3 { 4     //FileMode.OpenOrCreate   表示文件不存在,会创建一个新文件,存在会打开 5     using (Stream fs = new FileStream(@"D:\123.jpg", FileMode.OpenOrCreate)) 6     { 7         byte[] bt = new byte[fs.Length];  //声明存放字节的数组 8         while (true) 9         {10             var num = fs.Read(bt, 0, bt.Length);   //将流以byte形式读取到byte[]中11             if (num <= 0)12             {13                 break;14             }15         }16         fs.Close();17 18 19         //将 123.jpg 文件中读到byte[]中,然后写入到 456.jpg20         //FileAccess.ReadWrite  表示支持读和写操作21         using (Stream fs2 = new FileStream(@"D:\456.jpg", FileMode.OpenOrCreate, FileAccess.ReadWrite))22         {23             //设置字节流的追加位置从文件的末尾开始,如果文件不存在,只默认0开始24             fs2.Position = fs2.Length;25 26             //将待写入内容追加到文件末尾  27             fs2.Write(bt, 0, bt.Length);28 29             //关闭30             fs2.Close();31         }32     }33 }34 catch (Exception ex)35 {36     Console.WriteLine(ex.Message);37 }

生成效果如下

IO文件读写操作_IO文件读写_03