Asp.net C # read and write binary files using BinaryStream and BinaryWriter

Source: Internet
Author: User

The complete code is as follows:

 

Introduce namespace:

Using System. IO;

Complete code:

The code is as follows: Copy code

Namespace BinaryStreamApp
{ 
Class Program
    { 
Static void Main (string [] args)
        { 
// Open a binary writer for the file
FileStream fs;
Fs = new FileStream ("C: \ BinFile. dat", FileMode. OpenOrCreate, FileAccess. ReadWrite );
BinaryWriter bw = new BinaryWriter (fs );
// Prepare different types of data
Double aDouble = 1234.56;
Int aInt = 34567;
Char [] aCharArray = {'A', 'B', 'C '};
// Write data using multiple reloads of the Write method
Bw. Write (aDouble );
Bw. Write (aInt );
Bw. Write (aCharArray );
Int length = Convert. ToInt32 (bw. BaseStream. Length );
Fs. Close ();
Bw. Close ();
// Read and output data
Fs = new FileStream ("C: \ BinFile. dat", FileMode. OpenOrCreate, FileAccess. Read );
BinaryReader br = new BinaryReader (fs );
Console. WriteLine (br. ReadDouble (). ToString ());
Console. WriteLine (br. ReadInt32 (). ToString ());
Char [] data = br. ReadChars (length );
For (int I = 0; I <data. Length; I ++)
            { 
Console. WriteLine ("{0, 7: x}", data [I]);
            } 
Fs. Close ();
Br. Close ();
Console. ReadLine ();
        } 
    } 
} 

Running effect:

When an Int32 variable aInt is written, the system automatically calls the Write (Int32) method and writes a 4-byte signed integer to the file stream. When reading data, the ReadInt32 () method is called, read 4-byte data from a file stream.

It can be seen that the BinaryReader and BinaryWriter objects are very convenient to write and read data of fixed length types such as integer and floating point type to the stream.

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.