In this post I want to teach you how to use StreamReader and StreamWriter in c# an efficient way.
So what you need first, is to include the System.IO library to your project.
This step is really easy, we just need to type the following above the class section:
Now that we have this include we dont have to type System.IO.StreamReader / StreamWriter
each time we want to use them. We can now go with just typing StreamReader or StreamWriter
Next comes using the StreamWriter:
// im going to use a random sentence as the string here String string_ = "This is a sample sentence"; // sw is the variable; ext is the file extension var sw = new StreamWriter("folder\\file.ext"); // \\ = \ sw.Write(string_); sw.Close(); // this fixes permission issues as we are closing the file
You could also get the input for the as the string:
string_ = Console.ReadLine();
Now comes using the StreamReader:
// string to carry the file-string String FileString = ""; // sw is the variable; ext is the file extension var sr = new StreamReader("folder\\file.ext"); // \\ = \ FileString = sr.ReadToEnd(); // you can go with ReadLine to read the next line sr.Close(); // this fixes permission issues as we are closing the file // you can also read out the FileString Console.Write(FileString);
So I hope this was a helpful post for you. Please respond with a comment if you liked it!