C#文件流的读写

时间:2023-03-09 00:23:29
C#文件流的读写

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

  1.定义一个写文件流

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

  3.完成字符串转byte数组

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

  5.关闭文件流

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

  1.定义一个读文件流

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

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

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

  5.关闭文件流

具体代码如下:

 using System;
using System.IO;
using System.Text;
namespace LearnFileStream
{
class Program
{
string path = @"E:\AdvanceCSharpProject\LearnCSharp\LearnFileStream.txt"; private void TestWrite()
{
//定义写文件流
FileStream fsw = new FileStream(path, FileMode.OpenOrCreate);
//写入的内容
string inputStr = "Learn Advanced C Sharp";
//字符串转byte[]
byte[] writeBytes = Encoding.UTF8.GetBytes(inputStr);
//写入
fsw.Write(writeBytes, , writeBytes.Length);
//关闭文件流
fsw.Close();
} private void TestRead()
{
//定义读文件流
FileStream fsr = new FileStream(path, FileMode.Open);
//开辟内存区域 1024 * 1024 bytes
byte[] readBytes = new byte[ * ];
//开始读数据
int count = fsr.Read(readBytes, , readBytes.Length);
//byte[]转字符串
string readStr = Encoding.UTF8.GetString(readBytes, , count);
//关闭文件流
fsr.Close();
//显示文件内容
Console.WriteLine(readStr);
}
static void Main(string[] args)
{
new Program().TestWrite();
new Program().TestRead();
}
}
}