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

来源:互联网 发布:c语言闰年计算方法 编辑:程序博客网 时间:2024/05/16 04:25

编写流

.NET Framework 4.5             
其他版本                             
        
  • .NET Framework 4        
  • .NET Framework 3.5        
  • .NET Framework 2.0        
此主题尚未评级- 评价此主题                        

备份存储区是一个存储媒介,例如磁盘或内存。             每个不同的备份存储区都实现其自己的流作为 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);            }        }    }}
0 0