Implementation Code for reading and writing files in asp.net

Source: Internet
Author: User

This article uses an example to describe how to implement file read/write operations in asp.net. Previously, when a file is read/write, append or overwrite, you only need to change the value of the first parameter to switch.

Writing can be divided into continued writing and overwriting. You only need to change the value of the first parameter to switch.

The Code is as follows:

The Code is as follows: Copy code

/// <Summary>
/// Write the content to a text file
/// </Summary>
/// <Param name = "count"> status to determine whether to continue or overwrite </param>
/// <Param name = "fileName"> file name </param>
/// <Param name = "content"> content </param>
/// <Returns> the returned error message or 1 indicates that the write is successful. </returns>
Public static string writeFile (bool bl, string fileName, string content)
{
Try
{
String pathName = System. Web. HttpContext. Current. Server. MapPath (fileName );
// This does not exist and will be automatically created
Using (StreamWriter sw = new StreamWriter (pathName, bl, Encoding. Default ))
{
Sw. Write (content );
Sw. Flush ();
Sw. Close ();
}
}
Catch (Exception ex)
{
Return ex. Message;
}
Return "1 ";
}

/// <Summary>
/// Read the text file content
/// </Summary>
/// <Param name = "fileName"> file name </param>
/// <Returns> returned content </returns>
Public static string readFile (string fileName)
{
String result = "";
Try
{
String pathName = System. Web. HttpContext. Current. Server. MapPath (fileName );
Using (StreamReader sr = new StreamReader (pathName, Encoding. Default ))
{
Result = sr. ReadToEnd ();
Sr. Close ();
}
}
Catch (Exception ex)
{
Return "0"; // ex. Message;
}
Return result;
}

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.