【发布时间】:2016-07-27 17:52:36
【问题描述】:
我制作了一个用于加密和解密消息的工具。并不是说我在为军队工作或其他什么,我只是对一个概念感兴趣。
它将每个字符转换为我个人的二进制格式。每个字符扩展为 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 字节的整个数组。我希望它只写存储的字符(即直到最后一个非零字符的所有内容)。然后阅读器应该对应,从文件中读取字符并将它们完全按照导出时的状态放入数组中。
那么问题来了,我该怎么做呢?
【问题讨论】:
-
你正在尝试使用
if(binaryStr[x]),它不起作用吗? -
我打算提前终止循环...只是不知道该去哪里。
-
是的,那你遇到了什么问题?
-
没问题,因为我没有完成尝试。正如我所说,我不知道该怎么做。我是什么时候来到这里的。
-
你可以
continue(跳过第X个短值)或break完全循环。
标签: c# binary short binaryreader binarywriter