1

我有一个奇怪的问题。我想将可见的 textBox.Text 写入 FormClosing 上的“ini”文件(就在表单关闭之前),所以我在主表单的“属性”面板下双击了该事件并填充了相关函数,如下所示:

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        // store the whole content in a string
        string settingsContent = File.ReadAllText(settingsPath + "CBSettings");

        // replace a name with another name, which truly exists in the ini file 
        settingsContent.Replace(userName, userNameBox.Text);
        
        // write and save the altered content back to the ini file
        // settingsPath looks like this @"C:\pathToSettings\settingsFolder\"
        File.WriteAllText(settingsPath + "CBSettings", settingsContent);
    }

表单启动时没有问题,但不会通过单击 x 按钮退出。只有当我注释掉 File.WriteAllText 行时,它才会正确关闭。如果我只是停止调试,文件内容也不会改变。

编辑 :

实际问题是我用来从 ini 文件中查找并返回用户名的函数:

    public static string GetTextAfterTextFromTextfile(string path, string file, string fileExtension, string textToLookFor)
    {
        string stringHolder;
        StreamReader sr = File.OpenText(path + file + fileExtension);
        while((stringHolder = sr.ReadLine()) != null)
        {
            if(stringHolder.Contains(textToLookFor))
            {
                return stringHolder.Replace(textToLookFor, "");
            }
        }
        sr.Close();
        return "Nothing found";
    }

ini文件内容:

用户名 = SomeName

机器人名称 = SomeName

我从stackoverflow复制了上面的函数。我确信它有效,因为它按照我的意愿捕获了“SomeName”。现在我使用另一个函数(也来自stackoverflow),它在ini文件中搜索'User Name ='并返回紧随其后的文本。

    public static string GetTextAfterTextFromTextfile(string path, string textToSkip)
    {
        string str = File.ReadAllText(path);
        string result = str.Substring(str.IndexOf(textToSkip) + textToSkip.Length);
        return result;
    }

问题是,它返回

SomeNameBot 名称 = SomeName

关于如何限制string result为一行的任何提示?提前谢谢了!

4

1 回答 1

3

这是 64 位版本的 Windows 7 上的正常故障,由该操作系统的 Wow64 模拟器中的一个严重缺陷引起。不仅限于 Winforms 应用程序,C++ 和 WPF 应用程序也会受到影响。对于 .NET 应用程序,只有在附加了调试器时才会出现这种行为。复制代码:

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    throw new Exception("You will not see this");
}

抛出异常并且您无法再关闭窗口时,调试器不会停止。我在这篇文章中写了一个关于这个问题的更广泛的答案,包括推荐的解决方法。

在您的情况下快速修复:使用 Debug + Exceptions,勾选 Throw 复选框。现在,当抛出异常时调试器停止,允许您诊断和修复错误。

于 2014-09-13T09:50:50.193 回答