1.添加命名空间
System.IO;
System.Text;
2.文件的读取
(1).使用FileStream类进行文件的读取,并将它转换成char数组,然后输出。
byte[] byData = new byte[100];
char[] charData = new char[1000];
public void Read()
{
try
{
FileStream file = new FileStream("E:\\test.txt", FileMode.Open);
file.Seek(0, SeekOrigin.Begin);
file.Read(byData, 0, 100); //byData传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.
Decoder d = Encoding.Default.GetDecoder();
d.GetChars(byData, 0, byData.Length, charData, 0);
Console.WriteLine(charData);
file.Close();
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
}
(2).使用StreamReader读取文件,然后一行一行的输出。
public void Read(string path)
{
StreamReader sr = new StreamReader(path,Encoding.Default);
String line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line.ToString());
}
}
3.文件的写入
(1).使用FileStream类创建文件,然后将数据写入到文件里。
public void Write()
{
FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
//获得字节数组
byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!");
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
(2).使用FileStream类创建文件,使用StreamWriter类,将数据写入到文件。
public void Write(string path)
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.Write("Hello World!!!!");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
以上就完成了,txt文本文档的数据读取与写入。
案例二:https://www.cnblogs.com/zoujinhua/p/11325062.html
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 }
