StreamWriter Doesn't Work In C #

This piece of code worked fine in VS 2010. Now that I have VS 2013, it no longer writes the file. This is not a mistake or anything else. (I get a warning in Notepad ++ stating that the file has been updated but nothing has been written.)

Everything looks good to me. Any ideas?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { String line; try { //Pass the file path and file name to the StreamReader constructor StreamReader sr = new StreamReader("C:\\Temp1\\test1.txt"); StreamWriter sw = new StreamWriter("C:\\Temp2\\test2.txt"); //Read the first line of text line = sr.ReadLine(); //Continue to read until you reach end of file while (line != null) { //write the line to console window Console.WriteLine(line); int myVal = 3; for (int i = 0; i < myVal; i++) { Console.WriteLine(line); sw.WriteLine(line); } //Write to the other file sw.WriteLine(line); //Read the next line line = sr.ReadLine(); } //close the file sr.Close(); Console.ReadLine(); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } finally { Console.WriteLine("Executing finally block."); } } } } 
+6
source share
2 answers

You need Flush() StreamWriter after recording.

By default, a StreamWriter is buffered, which means that it will not be displayed until it receives a Flush () or Close () call.

You can also try closing it as follows:

 sw.Close(); //or tw.Flush(); 

You can also see the StreamWriter.AutoFlush Property

Gets or sets a value indicating whether the StreamWriter will flush its buffer into the underlying stream after each call to StreamWriter.Write.

Another option, which is now very popular and recommended, is to use the using statement , which will take care of this.

Provides convenient syntax to ensure proper use of IDisposable objects.

Example:

 using(var sr = new StreamReader("C:\\Temp1\\test1.txt")) using(var sw = new StreamWriter("C:\\Temp2\\test2.txt")) { ... } 
+5
source

You need to close StreamWriter. Like this:

 using(var sr = new StreamReader("...")) using(var sw = new StreamWriter("...")) { ... } 

This closes the threads, even if an exception is thrown.

+7
source

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


All Articles