Csharp/C Sharp/File Stream/Stream Read Write

Материал из .Net Framework эксперт
Версия от 11:45, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A help program that uses a disk file to store help information

/*
C# A Beginner"s Guide
By Schildt
Publisher: Osborne McGraw-Hill
ISBN: 0072133295
*/
/*   
   Project 11-2   
   
   A help program that uses a disk file 
   to store help information. 
*/   
 
using System; 
using System.IO;  
 
/* The Help class opens a help file, 
   searches for a topic, and then displays 
   the information associated with that topic. */  
class Help { 
  string helpfile; // name of help file 
 
  public Help(string fname) { 
    helpfile = fname; 
  } 
 
  // Display help on a topic. 
  public bool helpon(string what) {  
    StreamReader helpRdr; 
    int ch; 
    string topic, info; 
 
    try { 
      helpRdr = new StreamReader(helpfile); 
    } 
    catch(FileNotFoundException exc) { 
      Console.WriteLine(exc.Message); 
      return false; 
    } 
 
    try { 
      do { 
        // read characters until a # is found 
        ch = helpRdr.Read(); 
 
        // now, see if topics match 
        if(ch == "#") { 
          topic = helpRdr.ReadLine(); 
          if(what == topic) { // found topic 
            do { 
              info = helpRdr.ReadLine(); 
              if(info != null) Console.WriteLine(info); 
            } while((info != null) && (info != "")); 
            helpRdr.Close(); 
            return true; 
          } 
        } 
      } while(ch != -1); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message); 
    }  
    helpRdr.Close(); 
    return false; // topic not found 
  }  
  
  // Get a Help topic. 
  public string getSelection() {  
    string topic = ""; 
 
    Console.Write("Enter topic: ");   
    try {   
      topic = Console.ReadLine(); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message); 
      return ""; 
    } 
    return topic; 
  } 
}  
  
// Demonstrate the file-based Help system. 
public class FileHelp {   
  public static void Main() {   
    Help hlpobj = new Help("helpfile.txt");  
    string topic; 
 
    Console.WriteLine("Try the help system. " + 
                       "Enter "stop" to end.");  
    do {  
      topic = hlpobj.getSelection();   
 
      if(!hlpobj.helpon(topic)) 
        Console.WriteLine("Topic not found.\n"); 
 
    } while(topic != "stop"); 
  }  
}
/*
#if
if(condition) statement;
else statement;
#switch
switch(expression) {
  case constant:
    statement sequence  
    break;  
    // ...  
  }  
#for
for(init; condition; iteration) statement;  
#while
while(condition) statement;  
#do
do {  
  statement;  
} while (condition);  
#break
break; or break label;  
#continue
continue; or continue label;  
#goto
goto label;
 
*/


A simple key-to-disk utility that demonstrates a StreamWriter

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/* A simple key-to-disk utility that 
   demonstrates a StreamWriter. */ 
 
using System; 
using System.IO; 
  
public class KtoD { 
  public static void Main() { 
    string str; 
    FileStream fout; 
 
    try { 
      fout = new FileStream("test.txt", FileMode.Create); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message + "Cannot open file."); 
      return ; 
    } 
    StreamWriter fstr_out = new StreamWriter(fout); 
 
    Console.WriteLine("Enter text ("stop" to quit)."); 
    do { 
      Console.Write(": "); 
      str = Console.ReadLine(); 
 
      if(str != "stop") { 
        str = str + "\r\n"; // add newline 
        try { 
          fstr_out.Write(str); 
        } catch(IOException exc) { 
          Console.WriteLine(exc.Message + "File Error"); 
          return ; 
        } 
      } 
    } while(str != "stop"); 
 
    fstr_out.Close(); 
  } 
}


Asynchronously reads a stream

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Async.cs -- Asynchronously reads a stream
//
//             Compile this program with the following command line;
//                 C:>csc Async.cs
//
using System;
using System.IO;
using System.Threading;
namespace nsStreams
{
    public class Async
    {
        static Byte [] data = new Byte[64];
        static bool bDone = true;
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            FileStream istrm;
            try
            {
                istrm = new FileStream (args[0], FileMode.Open,
                                        FileAccess.Read, FileShare.Read,
                                        data.Length, true);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine (args[0] + " was not found");
                return;
            }
            catch (Exception)
            {
                Console.WriteLine ("Cannot open " + args[0] +
                                   " for reading");
                return;
            }
            AsyncCallback cb = new AsyncCallback (ShowText);
            long Length = istrm.Length;
            int count = 0;
            while (true)
            {
                if (Length == istrm.Position)
                    break;
                if (bDone)
                {
                    bDone = false;
                    istrm.BeginRead (data, 0, data.Length, cb, count);
                    ++count;
                }
                Thread.Sleep (250);
            }
            istrm.Close ();
        }
        static public void ShowText (IAsyncResult result)
        {
            for (int x = 0; x < data.Length; ++x)
            {
                if (data[x] == 0)
                    break;
                Console.Write ((char) data[x]);
                data[x] = 0;
            }
            bDone = true;
        }
    }
}


Catch file read exception and retry

 
using System;
using System.IO;
class Retry {
    static void Main() {
        StreamReader sr;
        int attempts = 0;
        int maxAttempts = 3;
    GetFile:
        Console.Write("\n[Attempt #{0}] Specify file " + "to open/read: ", attempts + 1);
        string fileName = Console.ReadLine();
        try {
            sr = new StreamReader(fileName);
            string s;
            while (null != (s = sr.ReadLine())) {
                Console.WriteLine(s);
            }
            sr.Close();
        } catch (FileNotFoundException e) {
            Console.WriteLine(e.Message);
            if (++attempts < maxAttempts) {
                Console.Write("Do you want to select another file: ");
                string response = Console.ReadLine();
                response = response.ToUpper();
                if (response == "Y") goto GetFile;
            } else {
                Console.Write("You have exceeded the maximum retry limit ({0})", maxAttempts);
            }
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}


Construct StreamWriter from FileSream

using System;
using System.IO;
public class IOExample
{
  static void Main() {   
    FileStream fs;
    StreamWriter sw;

    try {
      fs = new FileStream("practice.txt", FileMode.Open );
      sw = new StreamWriter(fs);
      // write a line to the file
      string newLine = "Not so different from you and me";
      sw.WriteLine(newLine);
      // close the streams
      sw.Close();
      fs.Close();
    } catch (IOException ioe) {
      Console.WriteLine("IOException occurred: "+ioe.Message);
    }
  }
}


Create a StreamWriter in UTF8 mode

 
using System;
using System.IO;
using System.Text;
class MainClass {
    static void Main() {
        using (FileStream fs = new FileStream("test.txt", FileMode.Create)) {
            using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) {
                w.WriteLine(124.23M);
                w.WriteLine("Test string");
                w.WriteLine("!");
            }
        }
        using (FileStream fs = new FileStream("test.txt", FileMode.Open)) {
            using (StreamReader r = new StreamReader(fs, Encoding.UTF8)) {
                Console.WriteLine(Decimal.Parse(r.ReadLine()));
                Console.WriteLine(r.ReadLine());
                Console.WriteLine(Char.Parse(r.ReadLine()));
            }
        }
    }
}


Demonstrates attaching a StreamReader object to a stream

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// StrmRdr.cs -- Demonstrates attaching a StreamReader object to a stream
//
//               Compile this program with the following command line:
//                   C:>csc StrmRdr.cs
using System;
using System.IO;
namespace nsStreams
{
    public class StrmRdr
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            FileStream strm;
            StreamReader reader;
            try
            {
                // Create the stream
                strm = new FileStream (args[0], FileMode.Open, FileAccess.Read);
                // Link a stream reader to the stream
                reader = new StreamReader (strm);
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                Console.WriteLine ("Cannot open " + args[0]);
                return;
            }
            while (reader.Peek() >= 0)
            {
                string text = reader.ReadLine ();
                Console.WriteLine (text);
            }
            reader.Close ();
            strm.Close ();
        }
    }
}


Demonstrates attaching a StreamWriter object to a stream

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// StrmWrtr.cs -- Demonstrates attaching a StreamWriter object to a stream
//
//                Compile this program with the following command line:
//                    C:>csc StrmWrtr.cs
using System;
using System.IO;
namespace nsStreams
{
    public class StrmWrtr
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            FileStream strm;
            StreamWriter writer;
            try
            {
// Create the stream
                strm = new FileStream (args[0], FileMode.OpenOrCreate, FileAccess.Write);
// Link a stream reader to the stream
                writer = new StreamWriter (strm);
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                Console.WriteLine ("Cannot open " + args[0]);
                return;
            }
            strm.SetLength (0);
            while (true)
            {
                 string str = Console.ReadLine ();
                 if (str.Length == 0)
                     break;
                 writer.WriteLine (str);
            }
            writer.Close ();
            strm.Close ();
        }
    }
}


illustrates reading and writing text data

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
 /*
  Example15_16.cs illustrates reading and writing text data
*/
using System;
using System.IO;
public class Example15_16 
{
  public static void Main() 
  {
    // create a new file to work with
    FileStream outStream = File.Create("c:\\TextTest.txt");
    // use a StreamWriter to write data to the file
    StreamWriter sw = new StreamWriter(outStream);
    // write some text to the file
    sw.WriteLine("This is a test of the StreamWriter class");
    // flush and close
    sw.Flush();
    sw.Close();
    // now open the file for reading
    StreamReader sr = new StreamReader("c:\\TextTest.txt");
    // read the first line of the file into a buffer and display it
    string FirstLine;
  
    FirstLine = sr.ReadLine();
    Console.WriteLine(FirstLine);
    // clean up
    sr.Close();
  }
}


Open a file using StreamWriter

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Open a file using StreamWriter.  
 
using System; 
using System.IO; 
  
public class KtoD1 { 
  public static void Main() { 
    string str; 
    StreamWriter fstr_out; 
 
    // Open the file directly using StreamWriter. 
    try { 
      fstr_out = new StreamWriter("test.txt"); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message + "Cannot open file."); 
      return ; 
    } 
 
    Console.WriteLine("Enter text ("stop" to quit)."); 
    do { 
      Console.Write(": "); 
      str = Console.ReadLine(); 
 
      if(str != "stop") { 
        str = str + "\r\n"; // add newline 
        try { 
          fstr_out.Write(str); 
        } catch(IOException exc) { 
          Console.WriteLine(exc.Message + "File Error"); 
          return ; 
        } 
      } 
    } while(str != "stop"); 
 
    fstr_out.Close(); 
  } 
}


Read data in line by line

 
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
class Program {
    static void Main(string[] args) {
        string strLine;
        try {
            FileStream aFile = new FileStream("Log.txt", FileMode.Open);
            StreamReader sr = new StreamReader(aFile);
            strLine = sr.ReadLine();
            while (strLine != null) {
                Console.WriteLine(strLine);
                strLine = sr.ReadLine();
            }
            sr.Close();
        } catch (IOException e) {
            Console.WriteLine("An IO exception has been thrown!");
            Console.WriteLine(e.ToString());
            return;
        }
    }
}


Reading from a text file line by line

 

using System;
using System.IO;
class MainClass {
    public static void Main(string[] args) {
        try {
            FileStream fs = new FileStream("c:\\a.txt", FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            string line = "";
            int lineNo = 0;
            do {
                line = sr.ReadLine();
                if (line != null) {
                    Console.WriteLine("{0}: {1}", lineNo, line);
                    lineNo++;
                }
            } while (line != null);
        } catch (Exception e) {
            Console.WriteLine("Exception in ShowFile: {0}", e);
        }
    }
}


StreamReader And Writer

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.IO;
namespace Client.Chapter_11___File_and_Streams
{
  public class StreamReaderAndWriter {
    static void Main(string[] args)
    {
      StreamReader MyStreamReader = new StreamReader(@"c:\Projects\Testing.txt");
      //If you need to control share permissions when creating a file you
      //use FileStream with StreamReader
      FileStream MyFileStream = new FileStream(@"c:\Projects\Testing.txt", FileMode.Open, FileAccess.Read, FileShare.None);
      StreamReader MyStreamReader2 = new StreamReader(MyFileStream);
      MyFileStream.Close();
      MyStreamReader2.Close();
      //The easiest way to Read a stream is to use the ReadLine method.
      //This method reads until it gets to the end of a line, but ...
      //it does not copy the carriage return line feed /n/r.
      string MyStringReader = MyStreamReader.ReadLine();
      //You can also read the whole file by using the following
      string MyStringReadToEOF = MyStreamReader.ReadToEnd();
      //The other route is to read one character at a time
      int[] MyArrayOfCharacters = new int[100];
      for (int i = 0; i < 99; i++)
      {
        MyArrayOfCharacters[i] = MyStreamReader.Read();
      }
      MyStreamReader.Close();
    }
  }
}


StreamReader.ReadLine

 
using System;
using System.IO;
public class MainClass {
    public static void Main() {
        FileStream fs2 = File.Create("Bar.txt");
        StreamWriter w2 = new StreamWriter(fs2);
        w2.Write("Goodbye Mars");
        w2.Close();
        fs2 = File.Open("Bar.txt", FileMode.Open, FileAccess.Read, FileShare.None);
        StreamReader r2 = new StreamReader(fs2);
        String t;
        while ((t = r2.ReadLine()) != null) {
            Console.WriteLine(t);
        }
        w2.Close();
        fs2.Close();
    }
}


The use of a buffered stream to serve as intermediate data holder for another stream

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// BufStrm.cs -- demonstates the use of a buffered stream to serve
//               as intermediate data holder for another stream.
//
//                Compile this program with the following command line:
//                    C:>csc BufStrm.cs
using System;
using System.IO;
namespace nsStreams
{
    public class BufStrm
    {
        static public void Main ()
        {
            FileStream strm;
            try
            {
                strm = new FileStream ("./BufStrm.txt",
                                       FileMode.OpenOrCreate,
                                       FileAccess.Write);
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                Console.WriteLine ("Cannot open ./BufStrm.txt");
                return;
            }
            strm.SetLength (0);
            BufferedStream bstrm = new BufferedStream (strm);
            string str = "Now is the time for all good men to " +
                         "come to the aid of their Teletype.\r\n";
            byte [] b;
            StringToByte (out b, str);
            bstrm.Write (b, 0, b.Length);
// Save the current position to fix an error.
            long Pos = bstrm.Position;
            Console.WriteLine ("The buffered stream position is "
                               + bstrm.Position);
            Console.WriteLine ("The underlying stream position is "
                               + strm.Position);
            str = "the quick red fox jumps over the lazy brown dog.\r\n";
            StringToByte (out b, str);
            bstrm.Write (b, 0, b.Length);
            Console.WriteLine ("\r\nThe buffered stream position is " +
                               bstrm.Position);
            Console.WriteLine ("The underlying stream position is still "
                               + strm.Position);
// Fix the lower case letter at the beginning of the second string
            bstrm.Seek (Pos, SeekOrigin.Begin);
            b[0] = (byte) "T";
            bstrm.Write (b, 0, 1);
// Flush the buffered stream. This will force the data into the
// underlying stream.
            bstrm.Flush ();
            bstrm.Close ();
            strm.Close ();
        }
//
// Convert a buffer of type string to byte
        static void StringToByte (out byte [] b, string str)
        {
            b = new byte [str.Length];
            for (int x = 0; x < str.Length; ++x)
            {
                b[x] = (byte) str [x];
            }
        }
    }
}

//File: BufStrm.txt
/*
Now is the time for all good men to come to the aid of their Teletype.
The quick red fox jumps over the lazy brown dog.
*/


Try and catch exceptions for StreamWriter

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 */
using System;
using System.IO;
namespace Client.Chapter_9___Exceptions_and_AppDomains
{
  public class MyMainClassChapter_9___Exceptions_and_AppDomains
  {
    delegate int MyDelegate(string s);
    static void Main(string[] args)
    {
      StreamWriter MyStream = null;
      string MyString = "Hello World";
      try
      {
        MyStream = File.CreateText("MyFile.txt");
        MyStream.Write(MyString);
      }
      catch (IOException e)
      {
        Console.WriteLine(e);
      }
      catch (Exception e)
      {
        Console.WriteLine(e);
      }
      finally
      {
        if (MyStream != null)
          MyStream.Close();
      }
    }
  }
  public class MyFile
  {
    public StreamWriter WriteText(string s)
    {
      if (!Valid(s))
        throw new IOException("Can"t Write String");
      else
        return new StreamWriter("c:\\test.txt");
    }
    public bool Valid(string s)
    {
      return false;
    }
  }
}


Use StreamWriter to create a text file

 
using System;
using System.IO;

public class MyStreamWriterReader {
    static void Main(string[] args) {
        StreamWriter writer = new StreamWriter("reminders.txt");
        writer.WriteLine("...");
        writer.WriteLine("Don"t forget these numbers:");
        for (int i = 0; i < 10; i++)
            writer.Write(i + " ");
        writer.Write(writer.NewLine);
        writer.Close();
        StreamReader sr = new StreamReader("reminders.txt");
        string input = null;
        while ((input = sr.ReadLine()) != null) {
            Console.WriteLine(input);
        }
    }
}


Using StreamWriter 3

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.IO;
namespace Client.Chapter_11___File_and_Streams
{
  public class UsingStreamWriter {
    static void Main(string[] args)
    {
      //StreamWriter can only be use to write to files or other streams
      StreamWriter MyStreamWriter = new StreamWriter(@"c:\Projects\Testing.txt");
      //You can also use FileStream with StreamWriter to provide a greater degree of control
      //in how you open the file
      FileStream MyFileStream = new FileStream(@"c:\Projects\Testing.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None);
      StreamWriter MyStreamWriter2 = new StreamWriter(MyFileStream);
      MyFileStream.Close();
      MyStreamWriter2.Close();
      //You can write sequentially to a file using this technique
      FileInfo MyFile = new FileInfo(@"c:\Projects\Testing.txt");
      StreamWriter MyStreamWriter3 = MyFile.CreateText();
      MyStreamWriter3.Close();
      //There are four overloaded ways to use StreamWriter.Write()
      //Writes a stream to a file
      string MyString = "Hello World";
      MyStreamWriter.Write(MyString);
      //Writes single characters to a stream
      char MyChar = "A";
      MyStreamWriter.Write(MyChar);
      //Writes an Array of characters
      char[] MyCharArray = new char[100];
      for (int i = 0; i < 99; i++)
      {
        MyCharArray[i] = (char)i;
      }
      MyStreamWriter.Write(MyCharArray);
      //or you can write a portion of an array
      MyStreamWriter.Write(MyCharArray, 25, 30);
      MyStreamWriter.Close();
    }
  }
}