Writing to a text file c#




















The following snippet is a better way to write Line 10 above, because the code becomes compatible across different machines. Combine Environment.

GetFolderPath Environment. Desktop , "WriteFile. By passing the filePath variable as an argument to the StreamWriter class, StreamWriter will create and write to the file in that location.

Note the use of the using statement on Line The using keyword ensures that the Dispose method of the referenced object is called, even if an exception occurs. In this case, it properly disposes of the StreamWriter object once the file write operation is complete. Line 16 will write the string Free C tutorials at wellsb.

This examples uses the WriteLine method, but the StreamWriter class also includes a Write method that will not include a newline character. These are similar to the Write and WriteLine methods of the Console class. Is this page helpful? Please rate your experience Yes No. Any additional feedback? Submit and view feedback for This product This page. View all page feedback. In this article.

The StreamWriter constructor takes a full file name and creates the file if it does not exist. The following code example uses a StreamWriter to create and write to a file. The WriteLine method of the StreamWriter writes the next line in the file. WriteLine "Monica Rathbun" ; writer. WriteLine "Vidya Agarwal" ; writer. WriteLine "Mahesh Chand" ; writer. WriteLine "Vijay Anand" ; writer. ReadAllText fullPath ; Console. WriteAllLines method writes a string array to a file. If the file is not created, it creates a new file.

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. The Console window displays the contents of the Sample. The following code uses the StreamWriter class to open, to write, and to close the text file. In a similar way to the StreamReader class, you can pass the path of a text file to the StreamWriter constructor to open the file automatically.

The WriteLine method writes a complete line of text to the text file.



0コメント

  • 1000 / 1000