6

ファイルに書き出す必要がある short の配列 (short[]) があります。これを行う最も簡単な方法は何ですか?

4

3 に答える 3

12

BinaryWriter を使用する

    static void WriteShorts(short[] values, string path)
    {
        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                foreach (short value in values)
                {
                    bw.Write(value);
                }
            }
        }
    }
于 2008-10-22T02:19:20.850 に答える
2

Jon B の回答に続いて、ファイルに他のデータが含まれている場合は、データの前に値の数を付けることをお勧めします。

すなわち:

static void WriteShorts(short[] values, string path)
{
    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            // Write the number of items
            bw.Write(values.Length);

            foreach (short value in values)
            {
                bw.Write(value);
            }
        }
    }
}
于 2008-10-22T02:28:01.347 に答える