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 ();
} |