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