// file IO using class StreamWriter
//
// SnippetCompiler.exe was used to write, compile (uses .NET V2 csc.exe)
// and test the code, this handy little utility is free from: 
// http://www.sliver.com/dotnet/SnippetCompiler/

using System;
using System.IO;  // TextWriter, StreamWriter

public class MyClass
{
  public static void Main()
  {
    string text;
    
    text = "Why Did the Chicken Cross the Road?\n";
    text += "ARISTOTLE: It is the nature of chickens to cross roads.\n";
    text += "RONALD REAGAN: I forget.\n";
    text += "CAPTAIN JAMES T. KIRK: To boldly go where no chicken has gone before.\n";
    text += "ERNEST HEMINGWAY: To die. In the rain.\n";
    text += "COLONEL SANDERS: I missed one?";
    
    // create a writer and open the file
    TextWriter tw = new StreamWriter("date.txt");
    
    // write a line of text (present date/time) to the file
    tw.WriteLine(DateTime.Now);
    
    // write the rest of the text lines
    tw.Write(text);
    
    // close the stream
    tw.Close();

    // read the text file back ...
    // create reader & open file
    TextReader tr = new StreamReader("date.txt");
    
    // read first line of text (here date/time)
    Console.WriteLine(tr.ReadLine());
    
    // read the text, next 2 lines
    Console.WriteLine(tr.ReadLine());
    Console.WriteLine(tr.ReadLine());
    
    // read the rest of the text lines
    Console.WriteLine(tr.ReadToEnd());
    
    // close the stream
    tr.Close();

    // wait to look at console display
    Console.Write("\nPress Enter to exit ...");
    Console.Read();

  }
}
3
Contributors
2
Replies
20
Views
9 Years
Discussion Span
Last Post by cVz
0
#
// create a writer and open the file
#
TextWriter tw = new StreamWriter("date.txt");

How do you want to convert a textwriter to a streamwriter like this ??

Maybe thats your problem dude

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.