Reading and Writing files is a commonly used function in projects. There are many implementation methods. I provide the most commonly used methods for release for reference by scholars.
1. Write files
/// <Summary> <br/> // write the file <br/> /// </Summary> <br/> /// <Param name = "content"> </param> <br/> // <Param name = "filesavepath"> </param> <br/> Public static void writefile (string content, string filesavepath) <br/>{< br/> If (file. exists (filesavepath) <br/>{< br/> file. delete (filesavepath); <br/>}< br/> filestream FS = file. create (filesavepath); <br/> byte [] bcontent = system. text. encoding. utf8.getbytes (content); <br/> FS. write (bcontent, 0, bcontent. length); <br/> FS. close (); <br/> FS. dispose (); <br/>}
2. Read files
/// <Summary> <br/> // obtain the file content <br/> /// </Summary> <br/> /// <Param name =" file "> </param> <br/> // <returns> </returns> <br/> Public static string getfilecontent (string file) <br/>{< br/> filestream FS = new filestream (file, filemode. open, fileaccess. read); <br/> streamreader sr = new streamreader (FS, encoding. utf8); <br/> stringbuilder output = new stringbuilder (); <br/> string RL; <br/> while ( (RL = Sr. Readline ())! = NULL) <br/>{< br/> output. append (RL + "<br>"); <br/>}< br/> Sr. close (); <br/> FS. close (); <br/> return output. tostring (); <br/>}
3. Write another file
/// <Summary> <br/> // XML Writing Method <br/> /// </Summary> <br/> /// <Param name = "Input "> content of the XML file to be written </param> <br/> // <Param name =" path "> the relative path is OK, no absolute path </param> <br/> Public void writelogfile (string input, string path) <br/>{< br/> // specify the directory of the log file <br/> string fname = server. mappath (PATH); <br/> // defines the object of File Information <br/> fileinfo finfo = new fileinfo (fname ); <br/> // determine whether the file exists <br/> If (finfo. exists) <br/>{< br/> // delete the file <br/> finfo. delete (); <br/>}< br/> // create a file-only stream. <br/> using (filestream FS = finfo. openwrite () <br/>{< br/> // create a write data stream based on the file stream created above <br/> streamwriter W = new streamwriter (FS ); <br/> // set the start position of the write data stream to the end of the file stream. <br/> W. basestream. seek (0, seekorigin. end); <br/> // write "file content" <br/> W. write (input); <br/> // Delete cache <br/> W. flush (); <br/> // close the stream <br/> W. close (); <br/>}
Learning and communication!