C# (Mono) – Reading and writing to a text file
File access is made simple with C# (Mono) on FreeBSD.
Reading a text file with C# (Mono)
To read a file, use a StreamReader
object. However, it is easy if you don’t do a new StreamWriter("File.txt")
but instead use File.OpenText("File.txt")
to create the StreamReader
. Once you have the stream, you just need to run the stream’s ReadToEnd()
function.
Here is a snippet to read a text file as a string.
1 2 3 4 | // Open the file into a StreamReader StreamReader file = File.OpenText( "SomeFile.txt" ); // Read the file into a string string s = file.ReadToEnd(); |
Now that you have the text file as a string, you can manipulate the string as you desire.
Writing to a text file with C# (Mono)
To write a text file, use StreamWriter.
1 2 3 4 5 | string str = "Some text" ; // Hook a write to the text file. StreamWriter writer = new StreamWriter( "SomeFile.txt" ); // Rewrite the entire value of s to the file writer.Write(str); |
You can also just add a line to the end of the file as follows:
1 2 3 4 5 | string str = "Some text" ; // Hook a write to the text file. StreamWriter writer = new StreamWriter( "SomeFile.txt" ); // Rewrite the entire value of s to the file writer.WriteLine(str); |
Example for learning
An example of these in a little project file made with MonoDevelop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | using System; using System.IO; namespace FileAccess { class MainClass { public static void Main ( string [] args) { string FileName= "TestFile.txt" ; // Open the file into a StreamReader StreamReader file = File.OpenText(FileName); // Read the file into a string string s = file.ReadToEnd(); // Close the file so it can be accessed again. file.Close(); // Add a line to the text s += "A new line.\n" ; // Hook a write to the text file. StreamWriter writer = new StreamWriter(FileName); // Rewrite the entire value of s to the file writer.Write(s); // Add a single line writer.WriteLine( "Add a single line." ); // Close the writer writer.Close(); } } } |
Well, this should get you started.
Good text
Nice and clear tutorial.
Thanks