Asp.net instance program for reading and writing files

Source: Internet
Author: User

1. File writing

It is a good idea to use FileWriter to randomly read files. StreamWriter can directly write strings to files to handle important conversions and write data to FileStream objects.

There are many ways to create StreamWriter:

The code is as follows: Copy code
FileStream File = new FileStream ("Log.txt", FileMode. CreateNew );
StreamWriter sw = new StreamWriter (File1 );

You can also directly create a StreamWriter object from the file:

The code is as follows: Copy code

StreamWriter sw = new StreamWriter ("Log.txt", true );

Example

The code is as follows: Copy code

// Address storage record path
String logFile = AppDomain. currentDomain. baseDirectory + @ "Log" + DateTime. now. toString ("yyyy") + "\" + DateTime. now. toString ("MM"); // address
// Determine whether a folder exists
If (! Directory. Exists (logFile ))
            {
Directory. CreateDirectory (logFile );
            }
// File path
LogFile = logFile + "\" + DateTime. Now. ToString ("dd") + ". txt ";
// Write an object
CreatFile (logFile, string. format ("rn ------ Log Start ------ rn Time: {0} rn data 1: {1} records rn Data 2: {2} records rn ------ Log end ------", DateTime. now, "", "");

Read files

The code is as follows: Copy code

/// <Summary>
/// Obtain the object content
/// </Summary>
/// <Param name = "file"> </param>
/// <Returns> </returns>
Public static string GetFileContent (string file)
        {
FileStream fs = new FileStream (file, FileMode. Open, FileAccess. Read );
StreamReader sr = new StreamReader (fs, Encoding. UTF8 );
StringBuilder output = new StringBuilder ();
String rl;
While (rl = sr. ReadLine ())! = Null)
            {
Output. Append (rl + "<br> ");
            }
Sr. Close ();
Fs. Close ();
Return output. ToString ();
        }

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.