Just a quick look at the way C# writes and reads text files.
Writing and reading a text file (C#)
// 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();
}
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.