C # - StreamWriter creates my file but no content

I try to use StreamWriter to register a search every time someone searches for my program. I can get StreamWriter to write a new file, but it does not create any content. I tried searching Google for the right use, and for me it looks like I did it right. If you can read my code and tell me where I am wrong, I will be very grateful!

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

Therefore, it should print a line something like lines: "title === $ 100.00"

+5
source share
1 answer

You have not closed the writer. The writer buffers the data, so if you just let it collect garbage without washing or closing it, the file descriptor will be closed without even writing data to the file.

Ideally, you should do this using the using statement:

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

Thus, 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 also suggest using File.WriteAllText if you want to write only one value to a file. You can also use TextWriter.WriteLine overloads, 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}"); 
+9
source

Source: https://habr.com/ru/post/1243521/


All Articles