c#中的流文件的编写 转自MSDN

本文介绍了.NET Framework中流的概念及使用方法,包括如何通过FileStream类读取文件内容,并利用StreamReader和BinaryReader类进行字符和字节级别的读取。同时探讨了备份存储区及其与流之间的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写流

.NET Framework 4.5             
此主题尚未评级 - 评价此主题                         

备份存储区是一个存储媒介,例如磁盘或内存。             每个不同的备份存储区都实现其自己的流作为 Stream 类的实现。  每个流类型也都从其给定的备份存储区读取字节并向其给定的备份存储区写入字节。  连接到备份存储区的流叫做基流。  基流具有的构造函数具有将流连接到备份存储区所需的参数。  例如,FileStream 具有指定路径参数(指定进程将如何共享文件的参数)等的构造函数。 

System.IO   类的设计提供简化的流构成。             可以将基流附加到一个或多个提供所需功能的传递流。  读取器或编写器可以附加到链的末端,这样便可以方便地读取或写入所需的类型。 

下面的代码示例围绕现有 MyFile.txt 创建 FileStream,为 MyFile.txt 提供缓冲。(请注意,默认情况下缓冲 FileStreams。)然后,创建 StreamReader 以读取 FileStream 中的字符,FileStream 将作为 StreamReader 的构造函数参数传递给它。             ReadLine   将进行读取,直到 Peek 再也找不到任何字符为止。 

C#
C++
VB
using System;
using System.IO;

public class CompBuf
{
    private const string FILE_NAME = "MyFile.txt";

    public static void Main()
    {
        if (!File.Exists(FILE_NAME))
        {
            Console.WriteLine("{0} does not exist!", FILE_NAME);
            return;
        }
        FileStream fsIn = new FileStream(FILE_NAME, FileMode.Open,
            FileAccess.Read, FileShare.Read);
        // Create an instance of StreamReader that can read
        // characters from the FileStream.
        using (StreamReader sr = new StreamReader(fsIn))
        {
            string input;
            // While not at the end of the file, read lines from the file.
            while (sr.Peek() > -1)
            {
                input = sr.ReadLine();
                Console.WriteLine(input);
            }
        }
    }
}


下面的代码示例围绕现有 MyFile.txt 创建 FileStream,为 MyFile.txt 提供缓冲。(请注意,默认情况下缓冲 FileStreams。)然后,创建 BinaryReader 以读取 FileStream 中的字节,FileStream 将作为 BinaryReader 的构造函数参数传递给它。             ReadByte   将进行读取,直到 PeekChar 再也找不到任何字节为止。 

C#
C++
VB
using System;
using System.IO;

public class ReadBuf
{
    private const string FILE_NAME = "MyFile.txt";

    public static void Main()
    {
        if (!File.Exists(FILE_NAME))
        {
            Console.WriteLine("{0} does not exist.", FILE_NAME);
            return;
        }
        FileStream f = new FileStream(FILE_NAME, FileMode.Open,
            FileAccess.Read, FileShare.Read);
        // Create an instance of BinaryReader that can
        // read bytes from the FileStream.
        using (BinaryReader br = new BinaryReader(f))
        {
            byte input;
            // While not at the end of the file, read lines from the file.
            while (br.PeekChar() > -1 )
            {
                input = br.ReadByte();
                Console.WriteLine(input);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值