TextWriter in C#

PHPz
Release: 2024-09-03 15:22:45
Original
187 people have browsed it

TextWriter is used to write text into a file. The following are some important points regarding TextWriter in C#, TextWriter is an abstract class under IO namespace. It is used to write a sequential series of characters into a file. It is the base class of StreamWriter and StringWriter which is used to write characters to streams and strings respectively.

By default, it is not thread-safe. As it is an abstract class, its object cannot be created. Any class implementing TextWriter must minimally implement its Write(Char) method to create its useful instance.

Syntax with explanation

TextWriter text_writer = File.CreateText(file_path);
Copy after login
Copy after login

The above statement creates a new file if it does not exist at the specified location (file_path). Then, we can use text_writer to call the methods of TextWriter class and can easily work with files in C#.

We can create TextWriter with using statement, such as:

using(TextWriter text_writer = File.CreateText(file_path))
{
//user code
}
Copy after login

It is better to use TextWriter with using the statement as it tells .NET to release the object specified in the using block once its work is done and it is no longer required.

How TextWriter works in C#?

To work with TextWriter, first, we need to import System.IO namespace. Now, we cannot directly create an instance of TextWriter using a ‘new’ keyword because it is an abstract class. Thus, to create the instance we use CreateText() method of the File class, such as:

TextWriter text_writer = File.CreateText(file_path);
Copy after login
Copy after login

This method takes the path of the file to be opened for writing. It creates or opens a file for writing UTF-8 encoded text. If the file already exists, then its content will be overwritten.

It returns an object of StreamWriter, which is the derived class of TextWriter and thus helps us creating an instance of TextWriter class. Now, with the help of this instance, we can call the methods of TextWriter to write text into a file.

TextWriter is a derived class of an abstract class MarshalByRefObject. Its inheritance hierarchy is as follows:

Object ——–> MarshalByRefObject ——–> TextWriter

Like StreamWriter there are other classes that are derived from the TextWriter class and provide the implementation for the members of TextWriter. Please find below the list of those derived classes with the help of which we can work with TextWriter:

  • IndentedTextWriter: It is used to insert a tab string and to track the current indentation level.
  • StreamWriter: It is used to write characters to a stream in a particular encoding.
  • StringWriter: It is used to write information to a string. The information is stored in an underlying StringBuilder.
  • HttpWriter: It provides an object of TextWriter class which can be accessed through the intrinsic HttpResponse object.
  • HtmlTextWriter: It is used to write mark up characters and text to an ASP.NET server control output stream.

Let us now discuss some important methods of TextWriter, such as:

Method Description
Close() It is used to close the current writer and it releases any system resources associated with that writer.
Dispose() It is used to release all the resources used by the TextWriter object.
Flush() It is used to clear all buffers for the current writer and causes any buffered data to be written to the underlying device.
Synchronized(TextWriter) It is used to create a thread-safe wrapper around the specified TextWriter.
Write(Char) It is used to write a character to the text stream.
Write(String) It is used to write the string to the text stream.
WriteAsync(Char) It is used to write the character to the text stream asynchronously.
WriteLine() It is used to write line terminator to the text stream.
WriteLineAsync(String) It is used to write the string to the text stream asynchronously followed by a line terminator.
Method
Description
Close() It is used to close the current writer and it releases any system resources associated with that writer.
Dispose() It is used to release all the resources used by the TextWriter object.
Flush() It is used to clear all buffers for the current writer and causes any buffered data to be written to the underlying device.
Synchronized(TextWriter) It is used to create a thread-safe wrapper around the specified TextWriter.
Write(Char) It is used to write a character to the text stream.
Write(String) It is used to write the string to the text stream.
WriteAsync(Char) It is used to write the character to the text stream asynchronously.
WriteLine() It is used to write line terminator to the text stream.
WriteLineAsync(String) It is used to write the string to the text stream asynchronously followed by a line terminator.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
string file = @"E:\Content\textWriter.txt";
// check if the file exists
try
{
if (File.Exists(file))
{
File.Delete(file);
}
// create the file
using (TextWriter writer = File.CreateText(file))
{
writer.WriteLine("TextWriter is an abstract class under " +
"System.IO namespace. It is used to write sequential " +
"series of characters into a file. It is the base class " +
"of StreamWriter and StringWriter which is used to " +
"write characters to streams and strings respectively. " +
"By default, it is not thread safe. " +
"As it is an abstract class, its object cannot be created. " +
"Any class implementing TextWriter must minimally implement " +
"its Write(Char) method to create its useful instance. ");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Copy after login

Output:

TextWriter in C#

We can asynchronously write characters to stream by using WriteAsync(Char) method such as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp2
{
public class Program
{
public static void Main(string[] args)
{
WriteCharAsync();
}
public static async void WriteCharAsync()
{
string file = @"E:\Content\textWriterAsync.txt";
try
{
//check if file already exists
if (File.Exists(file))
{
File.Delete(file);
}
using (StreamWriter writer = File.CreateText(file))
{
await writer.WriteLineAsync("TextWriter is an abstract class under "+
"System.IO namespace. It is used to write sequential " +
"series of characters into a file. It is the base class " +
"of StreamWriter and StringWriter which is used to " +
"write characters to streams and strings respectively. " +
"By default, it is not thread safe. " +
"As it is an abstract class, its object cannot be created. " +
"Any class implementing TextWriter must minimally implement " +
"its Write(Char) method to create its useful instance. ");
await writer.WriteLineAsync("We are writing characters " +
"asynchronously.");
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Copy after login

Output:

TextWriter in C#

Conclusion

TextWriter is used to write text or sequential series of characters to a file. A class derived from the TextWriter class needs to provide implementation to any of the members of the TextWriter. Write() methods of TextWriter with primitive data types as parameters write out values as strings.

The above is the detailed content of TextWriter in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!