File I/O operation instance in. net

Source: Internet
Author: User
Write to TXT text from Textbox Control Code
// Write from testbox to TXT text
Protected   Void Button5_click ( Object Sender, eventargs E)
{
String Text = Txtcontent. text;
If ( ! String . Isnullorempty (text ))
{
// Specify the full path of the file
String Filename = Server. mappath ( " ~ /TXT/test.txt " );
// Determine whether the file exists
If (File. exists (filename ))
{
//If yes, delete it first.
File. Delete (filename );
}
Else
{
// Create a file operation stream
Filestream stream =   New Filestream (filename, filemode. Create );
// Create a write operation stream
Streamwriter =   New Streamwriter (stream, encoding. utf8 );
// Write operation
Writer. Write (text );
// Clear the text in the control
Txtcontent. Text =   String . Empty;
// Close the stream. Otherwise, an exception occurs.
Writer. Close ();
Stream. Close ();
}
}
Else
{
Response. Write ("<SCRIPT> alert (\"Empty column! \") </SCRIPT>");
}
}

Then read the data from the generated test.txt and display it in the Textbox Control (same method) Code
// Read text to textbox display
Protected   Void Button6_click ( Object Sender, eventargs E)
{
String Filename = Server. mappath ( " ~ /TXT/test.txt " );
If (File. exists (filename ))
{
Filestream stream =   New Filestream (filename, filemode. Open );
Streamreader =   New Streamreader (stream, encoding. utf8 );
Txtcontent. Text = Reader. readtoend ();
Reader. Close ();
Stream. Close ();
}
Else
{
Response. Write ("<SCRIPT> alert (\"No test.txt file exists! \") </SCRIPT>");
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.