Using C # To read and write files

Source: Internet
Author: User

To read an object, follow these steps:

1. Declare and use the openread of file to instantiate a file stream object, as shown below:

2. Prepare a byte array for storing the file content. fs. length will get the actual size of the file, as shown below:

3. Start reading. Call a method of a file stream to read data into the data array.

 
Filestream FS = file. openread (filename); or filestream FS = filestream (filename, filemode. open, fileaccess. read, fileshare. read); byte [] DATA = new byte [FS. length]; FS. read (data, 0, Data. length );

The following method provides a safer method than the preceding method to ensure that the file is fully read.

Public static void saferead (Stream stream, byte [] data) {int offset = 0; int remaining = data. length; // read the while (remaining> 0) {int READ = stream as long as the remaining bytes exist. read (data, offset, remaining); If (read <= 0) throw new endofstreamexception ("File Read to" + read. tostring () + "failed! "); // Reduce the remaining bytes remaining-= read; // increase offset + = read ;}}

In some cases, you do not know the actual length of the stream, such as the network stream. In this case, you can use a similar method to read the stream until the data in the stream is fully read. We can initialize a cache first, and then write the stream information read from the stream to the memory stream, as shown below:

Public static byte [] readfully (Stream stream) {// initialize a 32 K cache byte [] buffer = new byte [32768]; using (memorystream MS = new memorystream ()) {// After the returned results are returned, the dispose method of the object will be automatically recycled to release the memory. // The while (true) {int READ = stream will be read continuously. read (buffer, 0, buffer. length); // you can return the result if (read <= 0) return ms until the final 3 M data is read. toarray (); Ms. write (buffer, 0, read );}}}

Although the above examples are relatively simple and the results are not very obvious (most of them are correct), you may have been there for a long time. It doesn't matter this article.ArticleIt was originally intended for beginners. The following method provides a way to read a stream by specifying the cache length, although in many cases you can directly use stream. length indicates the length of the stream, but not all streams can.

Public static byte [] read2buffer (Stream stream, int bufferlen) {// if the specified buffer length is invalid, specify a default length as the cache size if (bufferlen <1) {bufferlen = 0x8000;} // initialize a cache zone byte [] buffer = new byte [bufferlen]; int READ = 0; int block; // read the cached data from the stream each time, knowing that the while (Block = stream. read (buffer, read, buffer. length-read)> 0) {// reset the read location read + = block; // check whether the cache is reached, check whether there is any information that can be read if (read = buffer. length ){ // Try to read a byte int nextbyte = stream. readbyte (); // If the read fails, the result can be returned if (nextbyte =-1) {return buffer ;} // adjust the array size to continue reading byte [] newbuf = new byte [buffer. length * 2]; array. copy (buffer, newbuf, buffer. length); newbuf [read] = (byte) nextbyte; buffer = newbuf; // buffer is a reference (pointer ), this is intended to reset the buffer pointer to a larger memory read ++;} // If the cache is too large, use ret to shrink the buffer read while before, then return byte [] ret = new byte [read]; array. copy (buffer, RET, read); return ret;} using system; using system. io; using system. collections; namespace textfilereader_csharp {class class1 {static void main (string [] ARGs) {streamreader objreader = new streamreader ("C: \ test.txt"); string Sline = ""; arraylist arrtext = new arraylist (); While (Sline! = NULL) {Sline = objreader. Readline (); If (Sline! = NULL) arrtext. Add (Sline);} objreader. Close (); foreach (string soutput in arrtext) console. writeline (soutput); console. Readline ();}}}

Self-http://www.aspxcs.net/HTML/2015072531.html

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.