0

我有这些文本框,用户在其中输入数据,然后按下按钮来处理数据。现在用户输入的数据很多并且给用户一些松弛我想让它成为可能每当你按下按钮时,应用程序保存数据,所以当你关闭应用程序并再次启动它时,文本框被填充与最后输入的数据。

我正在考虑使用 .txt 文件来保存数据。只有我发现了一些困难。问题之一是每次尝试运行我的应用程序时,我都会不断地从 microsoft .NET Framework 获得一个消息框。消息框说索引超出了数组的范围。即使我认为我的代码没有超出我的数组的范围。

这是我使用的代码:

首先,我声明了一个数组并用包含文本框内容的变量填充它:

string[]settings = new string[5];
settings[0] = openKey;
settings[1] = secretKey;
settings[2] = statusRequestPath;
settings[3] = statusRequestAPI;
settings[4] = setSeconds.ToString();

然后我使用以下代码将数据写入文本文件。

using (StreamWriter writeFile = new StreamWriter(@"C:\Audio Silence Detector\AudioSilenceDetector.txt"))
{
    foreach (string line in settings)
    {
        writeFile.WriteLine(line);
    }
}

并将 .txt 文件的文本放回应用程序中,我已将其放入表单加载中:

string[] lines = System.IO.File.ReadAllLines(@"C:\Audio Silence Detector\AudioSilenceDetector.txt");

tbOpenKey.Text = lines[0];
tbSecretKey.Text = lines[1];
tbStatusRequestPath.Text = lines[2];
tbStatusRequestAPI.Text = lines[3];
tbSeconds.Text = lines[4];

我将代码更改为此,它似乎解决了我遇到的问题:

            if (lines.LongLength == 5)
        {
            tbOpenKey.Text = lines[0];
            tbSecretKey.Text = lines[1];
            tbStatusRequestPath.Text = lines[2];
            tbStatusRequestAPI.Text = lines[3];
            tbSeconds.Text = lines[4];
        }
4

1 回答 1

3

问题在于文件加载。

string[] lines = System.IO.File.ReadAllLines(@"C:\Audio Silence Detector\AudioSilenceDetector.txt");

您不能确定lines现在包含 5 个元素。你可能应该检查一下。

if(lines.Length == 5)
{
    tbOpenKey.Text = lines[0];
    tbSecretKey.Text = lines[1];
    tbStatusRequestPath.Text = lines[2];
    tbStatusRequestAPI.Text = lines[3];
    tbSeconds.Text = lines[4];
}
else
{
    MessageBox.Show("Input Data is Wrong");
}
于 2013-10-08T09:46:52.700 回答