Stream problems [C #])

Source: Internet
Author: User
Stream problems [C #] (convert) (21:06:21)
Category: others' rocks
Two days ago, I encountered a file problem in C #. Article Give me some advice. First, transfer the original article ,:) ----------------------------------------------------------------------
 
        Io operations basically need to use stream-related subclasses. Therefore, csdn also asks many questions about this type of problem. In fact, for stream, the operation is relatively simple, as long as you pay a little attention to the details, I believe it will be handy when using it. 
        Stream-related issues are roughly divided into the following categories.
        Question 1: Basic operation problems;
        Question 2: coding problems;
        Problem 3: handling the problem at the end;
        Question 4: stream caching;
        Question 5: Resource release;
        The last question is how to use stream to update part of big file data.
                For question 1, basic operations are mainly caused by reading and writing, mainly when the file data is large and needs to be written or read cyclically. The correct read format 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 );
}
Most people make mistakes in the sentence "nrealread = FS. Read (bbuffer, 0, 1024);" when doing this for the first time. Assume that the offset of the second parameter is set for the stream, so the value should be accumulated, that is, the total number of bytes read at present. Here we need to understand the stream operation. When performing read or write operations, the stream cursor will automatically follow up based on the read or written bytes. Second, stream. read or stream. in the write method, the second parameter is for the first buffer parameter, rather than for stream, so do not make mistakes in this place.
 
        The basic problem is how to open the file. Some people often ask how to use two streams to open the same file at the same time. In fact, the default stream open mode is exclusive. Therefore, when the file is not specified as access and sharing, the file opening operation will be abnormal. Therefore, you need to follow the instructions I wrote above. Also, to specify the starting position of the current stream, you can use the seek method or set the position attribute.
For question 2, encoding problems. Some people use stream subclasses, such as streamreader, to open a text file and find that the read data is garbled. This is because the file contains Chinese characters, the encoding method is not specified when the file is opened. Because the English and Chinese encoding methods are different, when encoding is not specified, it may sometimes cause Chinese reading errors. In this case, you only need to use the constructor that contains the encoding parameter in the streamreader type. For example:
 
Using (streamreader sr = new streamreader (Yourfile, encoding. Default ))
        The default encoding method is used here, but it may not be suitable for your file encoding method. Therefore, you need to debug and change this parameter in practical applications.
Problem 3: stream tail handles the problem. This type of problem shows that the file will increase when the file is copied. Therefore, when using stream. Read and stream. Write, you must use the return value of the method to indicate the actual number of bytes for reading and writing, as shown in the previous article.
 
   // Read data
   Nrealread = FS. Read (bbuffer, 0, 1024 );
   // Output data
   Debug. writeline (encoding. Default. getstring (bbuffer, 0, nrealread ));
 
        In this case, "1024" is not used for output, but "nrealread" is used as a valid byte mark.
        For question 4, the stream cache problem is mainly manifested in writing. To avoid frequent Io operations and reduce efficiency, most streams adopt asynchronous writing, that is, stream objects must be provided with certain caches to temporarily store written data. However, the cache is limited. When the cache is full, subsequent data cannot be written, leading to data loss. In this case, you need to call stream. Flush to write the cached data to the file and clear the cache. In fact, this is not the only method. In some stream sub-classes, you can also set buffersize or set the autoflush attribute to implement automatic writing, therefore, you can select different methods as needed.
 
        For stream release problems, this may not only be a stream issue, but may be a bad habit caused by C # programming. Although C # resources are hosted, if stream is not released in time, when other threads or processes use this file, the file cannot be opened (because most streams are opened in exclusive mode), and the file is not closed in time, the occupied buffer cannot be released in time. Therefore, it is vital to develop a good habit. In fact, it is very easy to release stream, either display the call of its close and dispose methods, or use usingProgramBlock, as I wrote earlier.
 
        The last one is how to use stream to update large files. It is common that when a file is large, but few files need to be modified, you want to use stream to directly perform operations such as delete, insert, or replace at a certain position.
        There are roughly three types of file update operations. Here, we mainly consider the update location and the update data length.
 
        First, the content length is not limited for the extension operation at the end of the file;
        The second type is equal-byte replacement, with unlimited locations;
        The last one is that the location is not fixed, and the number of bytes is uncertain.
 
        The first two types mentioned above are easy to process. For the first type, you only need to add the append flag when setting filemode. The replacement of equal-byte values is simpler. You can directly find the specified position through stream. Seek and then call stream. Write.
 
        The last one is the most troublesome. A simple solution: create a temporary file and write the file while reading it. If you need to modify the file, read the file first, modify the file, and then write the file. After writing all the files, delete the old files and change the temporary file name to the original name.
  the solution is share, use a read stream and a write stream to directly manipulate the source file. It should be noted that, in order to ensure that the newly written data does not overwrite the data that has not been read, it is necessary to control the write position of the stream to be read. For example, the current location to be read is 800 bytes of the file, that is to say, 800 bytes have not been read for processing. At this time, after writing stream data, the stream position cannot exceed 800 bytes, if the write is cached, do not submit data that exceeds the 800 position through flush immediately. In general, two streams are used to operate the same file. Pay special attention to this point. If the processing is not good, it will cause an endless loop. 

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.