In C #, using has two functions. 1. Used as a command to reference namespaces, such as using system. IO;
2. As a statement, using defines a range. After exiting using, an object is automatically released after the end of the range, which plays a role of automatically releasing resources. For example, the author uses the writeline method in the streamwriter column to write data to a specified text file first, and then calls the readtoend method of streamreader to read data from the specified text file. When using the using statement, the system first allocates resources to the using code block. After the using code block is generated, the resources allocated to the code block are automatically released because of the using statement, it mainly plays a role in Automatic Resource release and reduces system overhead.
Static void main (string [] ARGs)
{
String strfile = appdomain. currentdomain. setupinformation. applicationbase + "\ test.txt ";
// Specify test.txt in the current example
Try
{
// Check whether the file exists. If yes, delete it first and assign new content to the specified text file.
If (file. exists (strfile ))
{
File. Delete (strfile );
}
// Instantiate streamwriter and write data to a text file
Using (streamwriter Sw = new streamwriter (strfile ))
{
Sw. writeline! ");
Sw. writeline ("poor and strong, don't fall into the cloud! ");
}
// Instantiate streamreader and use the readtoend method to read and output data from the text file from start to end
Using (streamreader sr = new streamreader (strfile ))
{
Console. writeline (Sr. readtoend ());
}
}
Catch (exception ex)
{
Console. writeline (ex. Message );
}
}