StreamWriter | C# Examples
StreamWriter is a class in C# that provides a convenient way to write text to a file. It is located in the System.IO namespace. The StreamWriter class creates a new file or overwrites an existing file with the specified encoding and writes text to it.
To use StreamWriter, you first need to create an instance of the class by passing the path of the file that you want to write to as a parameter to the constructor. You can then call the various methods of the StreamWriter class to write text to the file.
Some of the common methods of the StreamWriter class include Write(), WriteLine(), and Flush(). Write() writes a string to the file, WriteLine() writes a string followed by a line terminator to the file, and Flush() flushes the buffer to ensure that all the data is written to the file.
You should always close the StreamWriter object after you are done writing to the file to ensure that the file is properly closed and any buffered data is written to the file.
Following are some of the most commonly used methods of the StreamWriter class:
Write(string):
This method writes a string to the file without adding a line terminator.
This code creates a StreamWriter object to write to a file named "file.txt", writes the string "Python, Examples!" to the file, and then closes the StreamWriter object.
WriteLine(string):
This method writes a string to the file and adds a line terminator at the end.
This code creates a StreamWriter object to write to a file named "file.txt", writes the string "Python," followed by a line terminator, writes the string "Examples!" followed by another line terminator, and then closes the StreamWriter object.
Write(char):
This method writes a single character to the file.
This code creates a StreamWriter object to write to a file named "file.txt", writes the characters 'P', 'y', 't', 'h', 'o' and 'n' to the file, and then closes the StreamWriter object.
Write(int):
This method writes an integer to the file.
This code creates a StreamWriter object to write to a file named "file.txt", writes the integer 56 to the file, and then closes the StreamWriter object.
Flush():
This method flushes the buffer to the file, ensuring that all data is written to the file.
This code creates a StreamWriter object to write to a file named "file.txt", writes the string "Python, Examples!" to the file, flushes the buffer to ensure that the data is written to the file, and then closes the StreamWriter object.
C# StreamWriter append text
To append text to an existing file using the StreamWriter class in C#, you need to pass a second parameter to the StreamWriter constructor. The second parameter specifies whether to append to an existing file or overwrite it. If you set the second parameter to true, it will append text to the existing file.
This code creates a StreamWriter object to write to a file named "file.txt". The second parameter true indicates that the StreamWriter should append to the existing file instead of overwriting it. The WriteLine() method writes a string followed by a line terminator to the file, and the Close() method closes the StreamWriter object.
If the file "file.txt" already exists and contains the text "Python, Examples!", running the above code will append the text "This is appended text." to the end of the file, resulting in the file containing:
Note that if the file "file.txt" doesn't exist, the above code will create a new file and write "This is appended text." to it.
Write formatted string using C# StreamWriter
To write formatted strings to a file using the StreamWriter class in C#, you can use the Write() or WriteLine() method along with the String.Format() method.
In the above code, first create a StreamWriter object to write to a file named "file.txt". Then declare two integer variables num1 and num2, with values of 10 and 20 respectively. The WriteLine() method then writes a formatted string to the file using the String.Format() method. The placeholders {0}, {1}, and {2} correspond to the variables num1, num2, and num1 + num2 respectively.
If you run this code, it will write the following string to the file "file.txt":
You can use various formatting options in the placeholders to control how the variables are formatted in the output string. For example, you can use the {0:C} placeholder to format a number as a currency value, or the {0:D} placeholder to format a number as a decimal value.
In the above code, declare a double variable num with a value of 1234.56789. The WriteLine() method then writes a formatted string to the file using the {0:C} and {1:D} placeholders. The {0:C} placeholder formats num as a currency value, and the {1:D} placeholder formats the integer part of num as a decimal value.
If you run this code, it will write the following string to the file "file.txt":
C# StreamWriter.WriteAsync() method
The WriteAsync() method of the StreamWriter class in C# is an asynchronous method that writes a string to a file. This method returns a Task object that represents the asynchronous write operation.
Following an example of using the WriteAsync() method to write a string to a file asynchronously:
In this code, first create a StreamWriter object to write to a file named "file.txt". Then declare a string variable text with a value of "Python, Examples!". The WriteAsync() method writes the string to the file asynchronously, and the FlushAsync() method flushes the buffer to ensure that all the data is written to the file before closing the StreamWriter object.
Note that the await keyword is used before calling the WriteAsync() and FlushAsync() methods. This indicates that the current method should await the completion of the asynchronous write operation before continuing execution.
Using the WriteAsync() method can be beneficial when writing to a file in a UI application or a web application, where the main thread should not be blocked by I/O operations. By using asynchronous I/O operations, the application can continue to be responsive while the write operation is being performed in the background.
- Advantages of C#
- C# vs. Java: What Are Its Main Differences
- Advantages of C# over Python
- First C# Program | Hello World
- Difference between Console.Write and Console.WriteLine in C#
- How do I create a MessageBox in C#?
- C# Comments
- How to reverse a string in C#
- Palindrome in C# with Examples
- Fibonacci Series Program in C# with Examples
- C# Program to Print Number Triangle
- Get Integer Input from User in C# Console Application
- C# StringBuilder | Learn To Use C# StringBuilder Class
- C# HashMap (Dictionary)
- Ternary Operator (? :) in C# with Examples
- How To Sort Datatable in C#
- Struct Vs Class in C# | Differencees and Advantages
- Async And Await In C#
- IEnumerable in C# | Examples
- ref Vs out in C#
- How to remove item from list in C#?
- How to Add Items to a C# List
- StreamReader in C# |Examples
- C# Map Example
- Static Method In C# | Examples
- How to convert an Enum to a String in C#
- How to convert a string to an enum in C#
- How to filter a list in C#?