EN
此内容没有您的语言版本,但有英语版本。
2(共 6)对本文的评价是有帮助 - 评价此主题

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

The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than character strings. The following code example demonstrates writing data to and reading data from a new, empty file stream (Test.data). After creating the data file in the current directory, the associated BinaryWriter and BinaryReader are created, and the BinaryWriter 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 reads out the specified content.

Example

using System;
using System.IO;
class MyStream 
{
    private const string FILE_NAME = "Test.data";
    public static void Main(String[] args) 
    {
        // Create the new, empty data file.
        if (File.Exists(FILE_NAME)) 
        {
            Console.WriteLine("{0} already exists!", FILE_NAME);
            return;
        }
        FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);
        // Create the writer for data.
        BinaryWriter w = new BinaryWriter(fs);
        // Write data to Test.data.
        for (int i = 0; i < 11; i++) 
        {
            w.Write( (int) i);
        }
        w.Close();
        fs.Close();
        // Create the reader for data.
        fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
        BinaryReader r = new BinaryReader(fs);
        // Read data from Test.data.
        for (int i = 0; i < 11; i++) 
        {
            Console.WriteLine(r.ReadInt32());
        }
        r.Close();
        fs.Close();
    }
}

Robust Programming

If Test.data already exists in the current directory, an IOException is thrown. Use FileMode.Create to always create a new file without throwing an IOException.

See Also

本文是否对您有所帮助?
(1500 个剩余字符)
感谢您的反馈

社区附加资源

显示:
© 2014 Microsoft. 版权所有。