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


           
         
     


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.
“;
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.
“;
StringToByte (out b, str);
bstrm.Write (b, 0, b.Length);
Console.WriteLine (”
The 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. */ [/csharp]

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

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

  }

}



           
         
     


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: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

   
  

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

   
 

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