C# StreamReader/StreamWriter类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BYH371256/article/details/89352656

本章介绍:StreamReader/StreamWriter类;

命名空间:using System.IO

1、StreamReader/StreamWriter类:用来处理流数据,提供了高效的流读写功能。可以直接用字符串进行读写,而不用转换成字节数组。

2、特性

    FileStream是操作字节的,因此可以操作包括文本以外的其它各种文件;

    StreamReader和StreamWriter是操作字符的,因此只能操作文本文件;

    StreamReader和StreamWriter是专门用来操作文件的,如果只针对文件的话,用StreamReader和StreamWriter要比FileStream方便的多。

3、 FileStream类操作的是字节和字节数组,而Stream类操作的是字符数据。

这是这两种类的一个重要区别,如果你是准备读取byte数据的话,用StreamReader读取然后用 System.Text.Encoding.Default.GetBytes转化的话,,则可能出现数据丢失的情况,如byte数据的个数不对等。因此操作byte数据时要用FileStream。

string textContent = fileStream.ReadToEnd();
byte[] bytes = System.Text.Encoding.Default.GetBytes(textContent);

4、public bool EndOfStream { get; } 获取一个值,该值表示当前的流位置是否在流的末尾。

5、//读取数据

FileStream fs = new FileStream(@"demo.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs);
string line = sr.ReadLine();//直接读取一行
sr.Close();
sr.Dispose();
fs.Close();
Console.WriteLine(line);

//循环读取文件
static void Main(string[] args)
{
    string path = @"demo.txt";
    using (StreamReader sr = new StreamReader(path, Encoding.Default))//使用using 自动释放资源
    {
        while (!sr.EndOfStream)//判断是否读完文件
        {
            Console.WriteLine(sr.ReadLine());
        }
    }
    Console.ReadKey();
}

6、//写入数据

FileStream fs = new FileStream(@"demo.txt", FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("hello world");
sw.Close();
sw.Dispose();
fs.Close();//这里要注意fs一定要在sw后面关闭,否则会抛异常

//或者
static void Main(string[] args)
{
    //用StreamWriter写入一个文本文件
    string path = @"demo.txt";
    using (StreamWriter sw = new StreamWriter(path,false, Encoding.Default))
    {
        sw.WriteLine("hello world");
    }
}

猜你喜欢

转载自blog.csdn.net/BYH371256/article/details/89352656
今日推荐