How to effectively use C # to read files and solve Chinese garbled characters

Source: Internet
Author: User
// Method 1:
Streamreader din = new streamreader (@ "C: \ 1.txt", system. Text. encoding. getencoding (" gb2312 "));
String html = "";
While (DIN. Peek ()>-1)
... {
Html = HTML + din. readtoend ();
}
Din. Close ();

// Method 2:
Streamreader SR1 = new streamreader (system. Io. Stream) file. openread (filename), system. Text. encoding. Default );
Html = "";
While (sr1.peek ()>-1)
... {
Html = HTML + sr1.readline ();
}
Sr1.close ();

// Method 3:
Streamreader objreader = new streamreader (@ "C: \ 1.txt", system. Text. encoding. getencoding (" gb2312 "));
String Sline = "", html = "";
While (Sline! = NULL)
... {
Sline = objreader. Readline ();
If (Sline! = NULL)
HTML + = Sline;
}
Objreader. Close ();

--------------------------------------------------------------------------------
Csdn: how to effectively use C # to read files
How do you read files? Use stream reading. Yes, that's right. C # provides us with a very powerful class library.. net), which encapsulates almost all classes we can think of and we don't think of. Stream is a general means of reading files, so will you actually use it to read the data in the file? Can I really read it completely?
To read an object, follow these steps:
1. Declare and use the openread of file to instantiate a file stream object, as shown below:
Filestream FS = file. openread (filename );
Or
Filestream FS = filestream (filename, filemode. Open, fileaccess. Read, fileshare. Read );
2. Prepare a byte array for storing the file content. fs. length will get the actual size of the file, as shown below:
Byte [] DATA = new byte [fs. Length];
3. Wow! Read started. Call a method of file stream to read data to the data array.
FS. Read (data, 0, Data. Length );
Haha! We only wrote three sentences to read the content in the file, which is so concise! Yes. Code Can I really work as expected? The answer is: Almost yes! In most cases, the above Code works well, but we should note that the read method has a return value. Since there is a return value, it must be reasonable, if the preceding method is used, it can be a function without return values. The purpose of the returned value is to give us a chance to determine the actual size of the file to determine whether the file has been fully read. Therefore, the above Code cannot ensure that we have read all the bytes in the file (although in many cases it has been read ). 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 remaining bytes continuously.

While (remaining> 0) ... {

Int READ = stream. Read (data, offset, remaining );

If (read <= 0)

Throw new endofstreamexception ("File Read to" + Read. tostring () + "failed! ");

// Reduce the remaining bytes

Remaining-= read;

// Increase the offset

Offset + = read;

}

}

In some cases, you do not know the actual length of a stream, for example, a 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];

Public static byte [] readfully (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.

// Read continuously

While (true) ... {

Int READ = stream. Read (buffer, 0, buffer. Length );

// The result will be returned after the final 3 M data is read.

If (read <= 0)

Return Ms. 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 whether this article 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 with invalid length is specified, a default length is specified 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 every time until all the streams are read.

While (Block = stream. Read (buffer, read, buffer. Length-read)> 0) ... {

// Reset the read location

Read + = block;



// Check whether the cache boundary is reached and whether there is any information that can be read

If (read = buffer. length) ... {

// Try to read one byte

Int nextbyte = stream. readbyte ();



// If the read operation fails, the result is returned after the read operation is complete.

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), which is intended to reset the buffer pointer to a larger memory.

Read ++;

}

}

// If the cache size is too large, use ret to shrink the buffer read while before and then directly return

Byte [] ret = new byte [read];

Array. Copy (buffer, RET, read );

Return ret;

}

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.