BinaryReader和BinaryWriter用于动态短数组

时间:2016-04-07 03:27:45

标签: c# binary short binaryreader binarywriter

我制作了一个加密和解密邮件的工具。并不是说我是为军队或其他任何人工作,我只是对一个概念感兴趣。

它需要每个角色并将其转换为我的个人二进制格式。每个字符都扩展为16位,或short。这些短整数中的每一个都存储在一个数组中。

我的目标是将此数组写入二进制文件,并能够将其读回数组。

以下是我的开始:

//This is the array the encrypted characters are stored in.
short[] binaryStr = new short[32767];

//...

private void butSelInput_Click(object sender, EventArgs e)
{
    dialogImportMsg.ShowDialog();
}

private void dialogImportMsg_FileOk(object sender, CancelEventArgs e)
{
    using (BinaryReader reader = new BinaryReader(new FileStream(dialogImportMsg.FileName, FileMode.Open)))
    {
        for (short x = 0; x < (short)reader.BaseStream.Length; x++)
        {
            binaryStr[x] = reader.ReadInt16();
        }
    }
}

private void butExport_Click(object sender, EventArgs e)
{
    dialogExportMsg.ShowDialog();
}

private void dialogExportMsg_FileOk(object sender, CancelEventArgs e)
{
    using (BinaryWriter writer = new BinaryWriter(new FileStream(dialogExportMsg.FileName, FileMode.OpenOrCreate)))
    {
        for (int x = 0; x < binaryStr.Length; x++)
        {
            //if(binaryStr[x] 
            writer.Write(BitConverter.GetBytes(binaryStr[x]));
        }
    }
}

显然我错了,因为它不像我想要的那样工作。编写器可能正在工作,但它会写入整个数组,即65534字节。我希望它只写出存储的字符(即一切都是最后一个非零字符)。然后读者应该对应于此,从文件中读取字符并将它们完全按照导出时的方式放入数组中。

所以问题是,我该怎么做?

1 个答案:

答案 0 :(得分:0)

我决定只存储原始字符串的长度。我将它用于写循环,将其存储在文件中,稍后从文件中读取它。

    private void dialogImportMsg_FileOk(object sender, CancelEventArgs e)
    {
        using (BinaryReader reader = new BinaryReader(new FileStream(dialogImportMsg.FileName, FileMode.Open)))
        {
            binaryStrLen = reader.ReadInt16();
            for (short x = 0; x < binaryStrLen; x++)
            {
                binaryStr[x] = reader.ReadInt16();
            }
        }
    }

    private void butExport_Click(object sender, EventArgs e)
    {
        dialogExportMsg.ShowDialog();
    }

    private void dialogExportMsg_FileOk(object sender, CancelEventArgs e)
    {
        using (BinaryWriter writer = new BinaryWriter(new FileStream(dialogExportMsg.FileName, FileMode.OpenOrCreate)))
        {
            writer.Write(BitConverter.GetBytes(binaryStrLen));
            for (int x = 0; x < binaryStrLen; x++)
            {
                writer.Write(BitConverter.GetBytes(binaryStr[x]));
            }
        }
    }