Asynchronously reads a stream

image_pdfimage_print

/*
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; } } } [/csharp]

illustrates reading and writing text data

image_pdfimage_print


   
 
/*
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();

  }

}



           
         
     


StreamReader And Writer

image_pdfimage_print

/*
* 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:ProjectsTesting.txt”);

//If you need to control share permissions when creating a file you
//use FileStream with StreamReader
FileStream MyFileStream = new FileStream(@”c:ProjectsTesting.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(); } } } [/csharp]

Create a StreamWriter in UTF8 mode

image_pdfimage_print
   
  

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(&#039;!&#039;);
            }
        }
        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()));
            }
        }
    }
}

   
     


Construct StreamWriter from FileSream

image_pdfimage_print
   
 

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);
    }
  }
}

           
         
     


Catch file read exception and retry

image_pdfimage_print

using System;
using System.IO;

class Retry {
static void Main() {
StreamReader sr;

int attempts = 0;
int maxAttempts = 3;

GetFile:
Console.Write(”
[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); } } } [/csharp]

StreamReader.ReadLine

image_pdfimage_print
   
  
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();

    }
}