How to read a file effectively using C #

Source: Internet
Author: User

How to read a file effectively using C #
How do you usually read the file? Read with stream. Yes, C # provides us with a very powerful class library (again touted). NET), which encapsulates almost all of the classes we can think of and we didn't think of, stream is the general means of reading files, then you really use it to read the data in the file? Can you read it completely?

Usually we read a file using the following steps:

1. Declare and instantiate a file stream object using the OpenRead of file, as follows

FileStream fs = file.openread (filename);

Or

FileStream fs = FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);

2. Prepare a byte array that holds the contents of the file, FS. Length will get the actual size of the file, just like this

byte[] data = new BYTE[FS. Length];

3, Wow! Start reading, call a file stream for a method to read the data into an array

Fs. Read (data, 0, data. Length);

Oh! We only wrote 3 sentences can be the contents of the document is read intact, it is too concise! Can this code really work as you would expect? The answer is: almost possible! In most cases the above code works very well, but we should note that the Read method has a return value, since there is a return value so there must be a reason, if the above can be written as a function without a return value. I want to return the value of the purpose is to give us a chance to determine the actual size of the file read, so as to determine whether the file has been completely read. So the above code does not guarantee that we must have read all the bytes in the file (though in many cases it is done). The following method provides a more secure method than the one above to ensure that the file is fully read out

public static void Saferead (Stream stream, byte[] data) {

int offset=0;

int remaining = data. Length;

As long as the remaining bytes are read

while (Remaining > 0) {

int read = stream. Read (data, offset, remaining);

if (read <= 0)

throw new EndOfStreamException ("file read to" +read.) ToString () + "failed! ");

Reduce the number of bytes remaining

Remaining-= read;

Increase offset

Offset + = read;

}

}



In some cases you do not know the actual length of the stream such as: network flow. A similar method can be used to read the stream until the data inside the stream is fully read. We can initialize a cache first, and then write the stream read stream to the memory stream, just like this:

public static byte[] Readfully (Stream stream) {

Initialize a 32k cache

byte[] buffer = new byte[32768];

using (MemoryStream ms = new MemoryStream ()) {//Returns the result and automatically reclaims the Dispose method that called the object to free memory

Keep reading.

while (true) {

int read = stream. Read (buffer, 0, buffer. Length);

Until the last 3M data is read, the results can be returned.

if (read <= 0)

Return Ms. ToArray ();

Ms. Write (buffer, 0, read);

}

}

}



Although the above examples are relatively simple, the effect is not very obvious (most of them are right), perhaps you will already, it's okay this article is originally written for beginners.

The following method provides a way to read a stream using the specified cache length, although in many cases you can use Stream.length to get the length of the stream, but not all streams are available.

public static byte[] Read2buffer (Stream stream, int bufferlen) {

Specifies a default length as the cache size if a buffer of invalid length is specified

if (Bufferlen < 1) {

Bufferlen = 0x8000;

}

Initialize a buffer

byte[] buffer = new Byte[bufferlen];

int read=0;

int block;

Every time you read the cache size data from the stream, you know that all the streams are read

while (block = stream. Read (buffer, read, buffer. length-read)) > 0) {

Re-set the read position

Read + = block;



Check to see if the bounds of the cache are reached and check if there is any information that can be read

if (read = = buffer. Length) {

Attempt to read a byte

int nextbyte = stream. ReadByte ();



Read failure indicates that read completion can return the result

if (nextbyte==-1) {

return buffer;

}



Adjust array size prepare 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 is too large, use RET to shrink the buffer in front while reading and return directly

byte[] ret = new Byte[read];

Array.copy (buffer, ret, read);

return ret;

}

CSDN last article on how to use C # to read files very good technical article
Original address: Http://blog.csdn.net/NewOne1998/archive/2006/07/25/972966.aspxThis article tag:Programming experienceNewoneSource:Csdn.net

How do you usually read the file? Read with stream. Yes, C # provides us with a very powerful class library (again touted). NET), which encapsulates almost all of the classes we can think of and we didn't think of, stream is the general means of reading files, then you really use it to read the data in the file? Can you read it completely?
Usually we read a file using the following steps:
1. Declare and instantiate a file stream object using the OpenRead of file, as follows
FileStream fs = file.openread (filename);
Or
FileStream fs = FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);
2. Prepare a byte array that holds the contents of the file, FS. Length will get the actual size of the file, just like this
byte[] data = new BYTE[FS. Length];
3, Wow! Start reading, call a file stream for a method to read the data into an array
Fs. Read (data, 0, data. Length);
Oh! We only wrote 3 sentences to get the file inside.

C # Read File code

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 ();

How to read a file effectively using C #

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.