Search code examples
c#streamwriter

Saving information to a text file in C#


I am in the process of learning C# and hit a wall that shows I'm obviously missing something important. The line:

var objWriter = new System.IO.StreamWriter(fileName, False);

In the code below causes an error - the string variable fileName can't be converted to System.IO.Stream and False doesn't exist in the current context. Why?

string message = "Hi There!";
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string fileName = myDocs + "'\'Test.txt";

if (!System.IO.File.Exists(fileName))
{
    System.IO.File.Create(fileName).Dispose();
}
var objWriter = new System.IO.StreamWriter(fileName, False);
objWriter.Write(message);
Console.WriteLine("Message Saved");
objWriter.Close();

Solution

  • Fix: Replace False with false.

    Explanation: Here is a list of constructors that StreamWriter has. Notice that it either takes a Stream and an Encoding, or a String and Boolean.

    Since C# is case sensitive, it tries to look for an object called False somewhere in your code, which explains your first issue (False doesn't exist in the current context). But False is an object, not a boolean, so the compiler assumes that fileName is of type Stream (to fit with the signature), but alas, it doesn't know how to convert your string to a Stream, hence the second error.