C# console application output to file




















Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Feedback will be sent to Microsoft: By pressing the submit button, your feedback will be used to improve Microsoft products and services. Privacy policy. The Read a text file section of this article describes how to use the StreamReader class to read a text file.

The Write a text file example 1 and the Write a text file example 2 sections describe how to use the StreamWriter class to write text to a file. The following code uses the StreamReader class to open, to read, and to close the text file. You can pass the path of a text file to the StreamReader constructor to open the file automatically. The ReadLine method reads each line of text, and increments the file pointer to the next line as it reads. When the ReadLine method reaches the end of the file, it returns a null reference.

For more information, see StreamReader Class. On the File menu, point to New , and then select Project. On the Debug menu, select Start to compile and to run the application. C Console. SetOut and Console. SetIn Use Console. SetOut and SetIn. SetOut changes the target output of a console application. A console program can write its output to a file. With the Console.

SetOut method, we specify a StreamWriter as the output object. Then, when the program executes, all the Console. Write calls will be printed to the file. We can also use Console. SetIn to adjust the input source. As you can imagine, you can change the output of the Console class, which by default displays information on the screen, so that it is stored, for example, in a file.

From this moment, everything we send to the console application via Write or WriteLine not be shown in the window, but will be stored directly in the text file. Another alternative would be to combine both outputs so that we could display in real time the information is stored.

You may also be interested in Log4Net for your applications, which makes use of this functionality. Testing the console before changing the output Console. WriteLine "Hello world from the console! Set the new output Console.



0コメント

  • 1000 / 1000