1

我有几个配置表单,我从那里写入配置文件。如何将 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);
            }
        }
    }
4

3 回答 3

2

投射short以使用BinaryWriter.Write(short)

 wr.Write((short)numericUpDown1.Value);
于 2013-01-10T17:32:57.267 回答
1
using(var file =  File.Create("out.bin"))
using (var writer = new BinaryWriter(file))
{
    foreach (short value in list)
    {
        writer.Write(value);
    }
}
于 2013-01-10T17:35:32.320 回答
0

short 是一个 Int16,但如果 100 是你的最大值,你只需要 8 位和字节就可以了。这将占用使用short 的一半空间。

wr.Write((byte)numericUpDown1.Value);
于 2013-01-10T17:41:26.770 回答