Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 431
brutalitea Avatar asked Feb 21 '16 17:02

brutalitea


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

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}");
like image 190
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet