Stream in C #

Source: Internet
Author: User

IO Operations basically need to use the Stream -related subclasses, so this kind of problem in CSDN asked more. In fact, for the Stream , the operation is relatively simple, as long as the details of the treatment of a little attention, I believe in the use of it will be handy.

for Stream related questions, broadly divided into the following categories.

Problem one, the basic operation of the problem;

Question two, coding problems;

Problem three, tail processing problem;

question four,Stream caching issues;

Issue five, resource release issues;

last question, say how to use Stream to update the large file portion of the data.

For problem one, the basic operation of the problem, mainly reading and writing problems, mainly appear in the file data is relatively large, need to cycle to write or read the time. The correct reading at this time is as follows.

Open a file to read

using (FileStream fs = new FileStream (Yourfile,

FileMode.Open, FileAccess.Read,

Fileshare.none))

{

int nrealread = 0;

byte[] Bbuffer = new byte[1024];

Do

{

Read data

Nrealread = fs. Read (bbuffer, 0, 1024);

Output data

Debug.WriteLine (Encoding.Default.GetString (bbuffer, 0, Nrealread));

}while (Nrealread = = 1024);

}

nrealread = fs." Read (bbuffer, 0, 1024x768); " This sentence makes a mistake. It is assumed that the offset of the second parameter is set for stream , so it is assumed that the accumulated value should be used, That is, the total number of bytes currently read. Here you need to understand stream operation, when read or write operations, stream are automatically followed by the bytes read or written, followed by or stream.write The second parameter in the two methods is for the first buffer parameters, not for stream , so don't make mistakes in this place.

Open the same file. In fact, the default stream stream seek method or set position property to complete.

For issue two, the encoding problem. Some people use the subclass of Stream , such as StreamReader to open a text file, found that the data read is garbled, resulting in most of this reason because the file contains Chinese characters, while opening the file without specifying the encoding method. Because of the different encoding methods in English and Chinese, it is sometimes caused to read Chinese errors when the encoding is not specified. Just use the constructor with the Encoding parameter in the StreamReader type, for example:

using (StreamReader sr = new StreamReader (Yourfile, Encoding.default))

This only uses the system default encoding, but it may not be suitable for your file encoding, so you need to debug and transform this parameter in practical application.

The third problem is theStream tail processing problem. This type of problem shows that the file will grow when copying files. So when using stream.read and Stream.Write , the return value of the method is used to indicate the number of bytes actually read and written, as previously written.

Read data

Nrealread = fs. Read (bbuffer, 0, 1024);

Output data

Debug.WriteLine (Encoding.Default.GetString (bbuffer, 0, Nrealread));

at this time, the output is not "1024x768 "but instead of"Nrealread "As a valid identifier for the byte.

For issue four, theStream caches the problem, which is mainly manifested at the time of writing. In order to avoid frequent operation of IO and reduce efficiency, most streams use asynchronous write, that is, the stream object to be equipped with a certain cache, to temporarily save the written data. However, the cache is limited, and when the cache is full it causes subsequent write data to not be written, resulting in data loss. then you need to display the call Stream.flush method to write the cached data to the file and empty the cache. In fact, this is not the only way, in some of the Stream 's subclasses also provides a way to set buffersize , or provide a set of AutoFlush properties for automatic writing, etc. So here you can choose different ways to do it according to different needs.

For the release of stream , this is probably not just a matter of using stream , it may be a bad habit of using C # programming. While C # Resources are managed, the stream , if not released in a timely manner, can cause a phenomenon that cannot be opened when other threads or processes use the file (because the stream Most are opened in a unique way) and are not closed in time, and the Buffer used is not released in time.

So it's important to develop a good habit. Actually releasing the Stream is simple, either showing the call to its Close and Dispose methods, or using a using program block, as I wrote earlier.

The last one is how to use Stream to update large files. It is common to think that when a file is larger, but there are few parts that need to be modified, you want to do something like delete, insert, or replace directly in a location via Stream .

For a file update operation, roughly divided into three kinds, here is mainly to consider the location of the update and update the length of the data.

The first type of operation for file tail extension, the content length is not limited;

The second kind of equal byte substitution operation, the position is not limited;

The last one is the position is not fixed, the number of bytes is indeterminate.

The first two mentioned above, the processing is relatively simple. For the first type, add Append when setting FileMode . For the substitution of equal bytes, it is simpler to find the specified position directly through Stream.seek , and then call stream.write .

And the last one, is the most troublesome. A simple solution, create a temporary file, and then read one side of the writing, encountered the need to modify, read it first and then modify the last write. When all finished, delete the old file, modify the name of the temporary file is the original name.

the more troublesome solution is through share mode, with one read stream And a write stream manipulates source files directly. It is important to note that in order to ensure that the new data is not read out of the data, that is, to control the write stream The does not write more than the location you want to read. For example, the current location to read is the file's 800 bytes, which means stream after writing the data, the Stream cannot be positioned more than 800 Bytes, if the write is using a cache, then more than 800 location data do not immediately pass stream to manipulate the same file, pay special attention to this, and the process is not good to cause a dead loop.

Stream in 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.