The Console window displays the contents of the Sample.txt file: Hello world On the Debug menu, select Start to compile and to run the application. Continue to read until you reach end of fileĬonsole.WriteLine("Exception: " + e.Message) Ĭonsole.WriteLine("Executing finally block.") StreamReader sr = new StreamReader("C:\\Sample.txt") Pass the file path and file name to the StreamReader constructor Select Visual C# Projects under Project Types, and then select Console Application under Templates.Īdd the following code at the beginning of the Class1.cs file: using System.IO Īdd the following code to the Main method: String line On the File menu, point to New, and then select Project. For more information, see StreamReader Class.Ĭreate a sample text file in Notepad. When the ReadLine method reaches the end of the file, it returns a null reference. The ReadLine method reads each line of text, and increments the file pointer to the next line as it reads. You can pass the path of a text file to the StreamReader constructor to open the file automatically. The following code uses the StreamReader class to open, to read, and to close the 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 Read a text file section of this article describes how to use the StreamReader class to read a text file. Original product version: Visual Studio Original KB number: 816149 Summary This article helps you read from and write to a text file by using Visual C#.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |