如何将从外部文件加载的数据保存到程序中?

时间:2012-01-19 09:21:46

标签: c# database file-io load

基于以下功能,它用于从文件.dat加载数据。问题是每次加载新文件时,前一个文件都会被覆盖。如何将来自先前文件的数据存储在程序中,以便在加载新文件时,新数据将被添加到上一个文件中?

private void btnLoad_Click(object sender, EventArgs e)
{
    try
    {

        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "Data File (*.dat)|*.dat";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {

            TextReader f = new StreamReader(openFileDialog1.FileName);

            String line;

            this.letterData.Clear();
            this.letters.Items.Clear();

            while ((line = f.ReadLine()) != null)
            {
                int sampleSize = Form1.DOWNSAMPLE_HEIGHT * Form1.DOWNSAMPLE_WIDTH;
                char ch = char.ToUpper(line[0]);
                bool[] sample = new bool[sampleSize];

                int idx = 2;
                for (int i = 0; i < sampleSize; i++)
                {
                    if (line[idx++] == '1')
                        sample[i] = true;
                    else
                        sample[i] = false;
                }

                this.letterData.Add(ch, sample);
                this.letters.Items.Add("" + ch);
            }

            f.Close();
        }
        MessageBox.Show(this, "File Loaded");

    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.Message);
    }
}

1 个答案:

答案 0 :(得分:1)

删除以下行?

this.letterData.Clear();
this.letters.Items.Clear();

编辑:

或者更改为以下内容,以便在词典中使用唯一键

this.letterData.Add(string.Format("{0}_{1}", openFileDialog1.FileName, ch), sample);
this.letters.Items.Add(ch.toString());