如何将int16写入二进制文件?

时间:2013-01-10 17:30:49

标签: c# file binary

我有几个配置表单从我写入配置文件。 如何将int16写入文件,因为最大值为100,我想在文件中保存一个位置?

private void butSave_Click(object sender, EventArgs e)
    {
        if (valChanged == true)
        {
            Properties.Settings.Default.Save();
            Assembly assem = Assembly.GetEntryAssembly();
            string dir = Path.GetDirectoryName(assem.Location);
            string filePath = Path.Combine(dir, "./conf/config.dat");
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open);
                BinaryWriter wr = new BinaryWriter(fs);
                fs.Position = 0;
                wr.Write(checkBox1.Checked);
                wr.Write(checkBox2.Checked);
                fs.Position = 16;
                wr.Write(numericUpDown1.Value);
                wr.Write(numericUpDown2.Value);
                wr.Write(numericUpDown3.Value);
                wr.Write(numericUpDown4.Value);
                wr.Close();
                Form1 main = new Form1();
                main.Show();
                this.Close();
            }
            catch
            {
                MessageBox.Show("Would you like to create a new config file", "File not found!", MessageBoxButtons.YesNoCancel);
            }
        }
    }

3 个答案:

答案 0 :(得分:2)

转换为short以使用BinaryWriter.Write(short)

 wr.Write((short)numericUpDown1.Value);

答案 1 :(得分:1)

using(var file =  File.Create("out.bin"))
using (var writer = new BinaryWriter(file))
{
    foreach (short value in list)
    {
        writer.Write(value);
    }
}

答案 2 :(得分:0)

short是Int16,但如果100是你的最大值,你只需要8位,字节就可以工作。这将占用空间的一半,就像使用短片一样。

wr.Write((byte)numericUpDown1.Value);