How to effectively use C # to read files

Source: Internet
Author: User

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! Can this code 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! ");

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.