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"
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 ...
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'.
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? 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.
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}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With