C#文件流的读写


1.文件流写入的一般步骤

  1.定义一个写文件流

  2.定义一个要写入的字符串

  3.完成字符串转byte数组

  4.把字节数组写入指定路径的文件

  5.关闭文件流

2.文件流读入的一般步骤

  1.定义一个读文件流

  2.开辟一块足够大的字节数组内存空间

  3.把指定文件的内容读入字节数组

  4.完成字节数组转字符串操作

  5.关闭文件流

具体代码如下:

复制代码
 1 using System;
 2 using System.IO;
 3 using System.Text;
 4 namespace LearnFileStream
 5 {
 6     class Program
 7     {
 8         string path = @"E:\AdvanceCSharpProject\LearnCSharp\LearnFileStream.txt";
 9 
10         private void TestWrite()
11         {
12             //定义写文件流
13             FileStream fsw = new FileStream(path, FileMode.OpenOrCreate);
14             //写入的内容
15             string inputStr = "Learn Advanced C Sharp";
16             //字符串转byte[]
17             byte[] writeBytes = Encoding.UTF8.GetBytes(inputStr);
18             //写入
19             fsw.Write(writeBytes, 0, writeBytes.Length);
20             //关闭文件流
21             fsw.Close();
22         }
23 
24         private void TestRead()
25         {
26             //定义读文件流
27             FileStream fsr = new FileStream(path, FileMode.Open);
28             //开辟内存区域 1024 * 1024 bytes
29             byte[] readBytes = new byte[1024 * 1024];
30             //开始读数据
31            int count = fsr.Read(readBytes, 0, readBytes.Length);
32             //byte[]转字符串
33             string readStr = Encoding.UTF8.GetString(readBytes, 0, count);
34             //关闭文件流
35             fsr.Close();
36             //显示文件内容
37             Console.WriteLine(readStr);
38         }
39         static void Main(string[] args)
40         {
41             new Program().TestWrite();
42             new Program().TestRead();
43         }
44     }
45 }
复制代码


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM