C# StreamWriter Is Creating My File But No Content

I'm trying to use StreamWriter to log a search every time someone searches on my program. I can get StreamWriter to write a new file but it does not create any content. I've tried searching google for the proper use and to me it looks like I've done it correctly. If you can read my code and tell me where I am wrong then I will be very thankful!

StreamWriter write = new StreamWriter("searchLogFile.dat");
write.WriteLine(gameTitle + " === " + string.Format("{0:C}", saleValue));

So it should print a line something along the lines of: "TITLE === $100.00"

Jon Skeet
people
quotationmark

You haven't closed the writer. The writer buffers data, so if you just let it get garbage collected without flushing or closing it, the file handle will be closed without ever writing the data to the file.

You should ideally do this with a using statement:

using (StreamWriter write = new StreamWriter("searchLogFile.dat"))
{
    write.WriteLine(gameTitle + " === " + string.Format("{0:C}", saleValue));
}

That way the writer will be closed even if an exception is thrown. Get into the habit of using using statements for types that implement IDisposable.

I'd also suggest using File.WriteAllText if you only want to write one value to a file. You can also use the overloads of TextWriter.WriteLine which accept format strings to make this code simpler:

writer.WriteLine("{0} === {1:C"}, gameTitle, saleValue);

Or with C# 6:

writer.WriteLine($"{gameTitle} === {saleValue:C}");

Or all in one go:

File.WriteAllText("searchLogFile.dat", $"{gameTitle} === {saleValue:C}");

people

See more on this question at Stackoverflow