Asp.net c file writing function example code StreamWriter and StreamReader write characters to the stream and read characters from the stream. The following code example opens the log.txt file (create a file if the file does not exist) for input and attaches the information to the end of the file. Then write the file content to the standard output for display.
Asp tutorial. net c file writing function instance code
Streamwriter and streamreader write characters to the stream and read the characters from the stream. The following code example opens the log.txt file (create a file if the file does not exist) for input and attaches the information to the end of the file. Then write the file content to the standard output for display.
[C #]
Using system;
Using system. io;
Class dirappend
{
Public static void main (string [] args)
{
Streamwriter w = file. appendtext ("log.txt ");
Log ("test1", w );
Log ("test2", w );
// Close the writer and underlying file.
W. close ();
// Open and read the file.
Streamreader r = file. opentext ("log.txt ");
Dumplog (r );
}
Public static void log (string logmessage, textwriter w)
{
W. write ("rnlog entry :");
W. writeline ("{0} {1}", datetime. now. tolongtimestring (),
Datetime. now. tolongdatestring ());
W. writeline (":");
W. writeline (": {0}", logmessage );
W. writeline ("-------------------------------");
// Update the underlying file.
W. flush ();
}
Public static void dumplog (streamreader r)
{
// While not at the end of the file, read and write lines.
String line;
While (line = r. readline ())! = Null)
{
Console. writeline (line );
}
R. close ();
}
}
Read File 2
Using (filestream fs = new filestream (file, filemode. open, fileaccess. readwrite ))
{
Xmldocument toxml = new xmldocument ();
Toxml. load (fs );
// Do some modification for the xml.
Fs. flush ();
Toxml. save (fs );
}
For more details, see http://www.bKjia. c0m/net/c/33608.htm
Read File 3
Write files
Public static void writefile (string filepath, string str)
{
Streamwriter sr;
If (file. exists (filepath) // if the file exists, the file. appendtext object is created.
{
Sr = file. appendtext (filepath );
}
Else // if the file does not exist, the file. createtext object is created.
{
Sr = file. createtext (filepath );
}
Sr. writeline (str );
Sr. close ();
}