Try and catch exceptions for StreamWriter

image_pdfimage_print
   
 
/*
 * 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:	est.txt");
    }
    public bool Valid(string s)
    {
      return false;
    }
  }
}

           
         
     


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

image_pdfimage_print


   
 
/*
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.
"); 
 
    } 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;
 
*/
           
         
     


Open a file using StreamWriter

image_pdfimage_print


   
 
/*
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 + "
"; // add newline 
        try { 
          fstr_out.Write(str); 
        } catch(IOException exc) { 
          Console.WriteLine(exc.Message + "File Error"); 
          return ; 
        } 
      } 
    } while(str != "stop"); 
 
    fstr_out.Close(); 
  } 
}


           
         
     


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

image_pdfimage_print


   
 
/*
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 + "
"; // add newline 
        try { 
          fstr_out.Write(str); 
        } catch(IOException exc) { 
          Console.WriteLine(exc.Message + "File Error"); 
          return ; 
        } 
      } 
    } while(str != "stop"); 
 
    fstr_out.Close(); 
  } 
}


           
         
     


Demonstrates attaching a StreamWriter object to a stream

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


           
         
     


Demonstrates attaching a StreamReader object to a stream

image_pdfimage_print
   
 
/*
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

image_pdfimage_print

/*
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]