日期:2011-02-20  浏览次数:20501 次

Introduction
Reading and writing text files may sometimes be quite handy in programming. You might want to maintain your own text-style configuration files. Or edit autoexec.bat from your program. In .Net we have an abstract class called a Stream class which provides methods to read and write from a store. The FileStream class is a Stream class derived class which wraps the streaming functionality around a file. In this article I'll demonstrate how you can use this class along with several reader and writer classes to read from a file, write to a file, create a file and even retrieve information about a file. I have provided a commented program below.

The Program
using System;
using System.IO;
public class nishfiles
{
    public static void Main(String[] args)
    {
            //Create a file 'nish.txt' in the current directory
        FileStream fs = new FileStream("nish.txt" , FileMode.Create, FileAccess.ReadWrite);         
        
        //Now let's put some text into the file using the StreamWriter
        StreamWriter sw = new StreamWriter(fs);         
        sw.WriteLine("Hey now! Hey now!\r\nIko, Iko, unday");
        sw.WriteLine("Jockamo feeno ai nan ay?\r\nJockamo fee nan ay?");
        sw.Flush();
        
        //We can read the file now using StreamReader        
        StreamReader sr= new StreamReader(fs);
        sr.BaseStream.Seek(0, SeekOrigin.Begin);
        string s1;
        Console.WriteLine("about to read file using StreamReader.ReadLine()");
        Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
        while((s1 = sr.ReadLine())!=null)
            Console.WriteLine(s1);
        Console.WriteLine();
        
        //We can read the file now using BinaryReader        
        BinaryReader br= new BinaryReader (fs);
        br.BaseStream.Seek(0, SeekOrigin.Begin);
        Byte b1;
        Console.WriteLine("about to read file using BinaryReader.ReadByte()");
        Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
        while(br.PeekChar()>-1)
        {
            b1=br.ReadByte();
            Console.Write("{0}",b1.ToChar());
            if(b1!=13 && b1!=10)
                Console.Write(".");