IO文件读写操做

若是是操做文本文件类型数组

推荐使用:  StreamReader、StreamWriterapp

示例: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 }

若是文件不存在,会自动建立。编码

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

 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)          //读到最后会返回null
10             {
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 }

若是是操做 其余类型的文件(包括文本文件),能够使用 FileStream,3d

好比咱们操做一张图片文件code

 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.jpg
20         //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 }

生成效果以下blog

相关文章
相关标签/搜索