How to Use Textwriter in C#
Textwriter is a class in ASP.NET that allows users to interface with text files. The class gives programmers the ability to open, write, read, and close the text file for applications. Textwriter can be used for web applications or desktop applications for reporting and logging dynamic text files.
Instructions
-
-
1
Set up a variable that points to the file. The application needs to have a pointer to the text file for manipulation. This is completed through the use of the "FileInfo" class. Below is the code to open a text file:
FileInfo theFile = new FileInfo("myFilte.txt"); -
2
Open an instance of the "Streamwriter" class. Streamwriter inherits the main "Textwriter" class. Textwriter is a base class library that is usable through its members. In this example, the use of its "Streamwriter" member is used to manipulate the text file. The code below initiates an instance of the class by opening the file variable from step 1 for text insertion.
StreamWriter myStream = theFile.CreateText(); -
-
3
Insert some text. The file is ready for text insertion, which is completed through the "WriteLine()" function of the "Streamwriter" class.
myStream.WriteLine("This is my insertion text.");
myStream.Close();
The "Close()" function is used to free the file from being locked. It's the equivalent of trying to access a file when someone else already has it opened. In this instance, if the file isn't closed, the operating system has a lock on it and other users (including new instances of the application) are unable to use the file. -
4
Read the file. Streamwriter can also be used to read a file's text. The code below reads the file line-by-line and outputs the text to the console:
StreamReader myReader= File.OpenText("myFile.txt");
string fileLine = null;
while ((fileLine = myReader.ReadLine()) != null)
{
Console.WriteLine(fileLine);
}
myReader.close();
-
1