【问题标题】:how to save data loaded from external file into the program?如何将从外部文件加载的数据保存到程序中?
【发布时间】:2012-01-19 09:21:46
【问题描述】:

基于下面的函数,它用于从文件 .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);
    }
}

【问题讨论】:

    标签: c# database file-io load


    【解决方案1】:

    删除以下行?

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

    编辑:

    或更改为 te 以下以在您的字典中拥有唯一键

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

    【讨论】:

    • 是的,问题是,这个程序使用了一个字典功能,一个键只能保存一个值,如果没有应用清除功能,则无法加载新数据,它会显示错误'已添加具有相同键的项目'
    • 很好,但是通过清除字典,您可以明确删除您说需要维护的所有数据。您需要定义更好的标准来生成唯一键(例如,包括文件名?)或使用保存数据的不同结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    相关资源
    最近更新 更多