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:ProjectsTesting.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:ProjectsTesting.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:ProjectsTesting.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(); } } } [/csharp]

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&#039;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


   
 
/*
C# A Beginner&#039;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 == &#039;#&#039;) { 
          topic = helpRdr.ReadLine(); 
          if(what == topic) { // found topic 
            do { 
              info = helpRdr.ReadLine(); 
              if(info != null) Console.WriteLine(info); 
            } while((info != null) &amp;&amp; (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 &#039;stop&#039; 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


   
 
/*
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 (&#039;stop&#039; 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


   
 
/*
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 (&#039;stop&#039; 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

   
 
/*
C# Programming Tips &amp; 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

   
 
/*
C# Programming Tips &amp; 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 ();
        }
    }
}