2014-09-13 87 views
1

我有一个奇怪的问题。我想将可见的textBox.Text写到FormClosing上的一个“ini”文件中(就在表单关闭之前),所以我在主窗体的Properties面板中双击该事件并填充相关函数,如下所示:File.ReadAllText阻止窗体关闭x按钮单击

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文件中的'用户名='并返回紧随其后的文本。

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只有一个行中的任何提示?提前谢谢了!

+0

你确定它没有抛出异常吗?例如,它看起来像你试图保存到一个文件夹而不是文件? – 2014-09-13 08:05:24

+1

我没有在你的文件名中看到扩展名.Btw,看看try/catch.Then也许你可以得到有意义的错误信息而不是冻结窗口。 – 2014-09-13 08:05:47

+0

不,没有错误,它并没有被冻结,它只是不响应x按钮点击,因此不保存文件的任何内容。 – betaFlux 2014-09-13 08:08:00

回答

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"); 
} 

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

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

+1

Woooooooot,这是巨大的,非常有用的知道。 – 2014-09-13 10:32:46

+0

是的,谢谢你,确实非常有帮助,但实际上我的问题有另一个原因。我更新了我的问题。 – betaFlux 2014-09-13 16:54:41

+0

好吧,当然,一旦你知道如何恢复调试器,那么很容易发现真正的bug,不是吗?你是否冷落了这篇文章? – 2014-09-13 17:05:10