Export (0) Print
Expand All

How to: Read and Write to a Newly Created Data File

The BinaryWriter and System.IO::BinaryReader classes are used for writing and reading data rather than character strings. The following example demonstrates how to write data to, and read data from, a new, empty file stream called Test.data. After creating the data file in the current directory, the associated BinaryWriter and BinaryReader objects are created, and the BinaryWriter object is used to write the integers 0 through 10 to Test.data, which leaves the file pointer at the end of the file. After setting the file pointer back to the origin, the BinaryReader object reads out the specified content.

using namespace System;
using namespace System::IO;

ref class MyStream
{
private:
    static String^ FILE_NAME = "Test.data";

public:
    static void Main()
    {
        // Create the new, empty data file. 
        if (File::Exists(FILE_NAME))
        {
            Console::WriteLine("{0} already exists!", FILE_NAME);
            return;
        }
        FileStream^ fs = gcnew FileStream(FILE_NAME, FileMode::CreateNew);
        // Create the writer for data.
        BinaryWriter^ w = gcnew BinaryWriter(fs);
        // Write data to Test.data. 
        for (int i = 0; i < 11; i++)
        {
            w->Write(i);
        }
        w->Close();
        fs->Close();
        // Create the reader for data.
        fs = gcnew FileStream(FILE_NAME, FileMode::Open, FileAccess::Read);
        BinaryReader^ r = gcnew BinaryReader(fs);
        // Read data from Test.data. 
        for (int i = 0; i < 11; i++)
        {
            Console::WriteLine(r->ReadInt32());
        }
        fs->Close();
    }
};

int main()
{
    MyStream::Main();
}

If Test.data already exists in the current directory, an IOException exception is thrown. Use the file mode option FileMode::Create when you initialize the file stream to always create a new file without throwing an exception.

Show:
© 2014 Microsoft