我有一个奇怪的问题。我想将可见的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
只有一个行中的任何提示?提前谢谢了!
你确定它没有抛出异常吗?例如,它看起来像你试图保存到一个文件夹而不是文件? – 2014-09-13 08:05:24
我没有在你的文件名中看到扩展名.Btw,看看try/catch.Then也许你可以得到有意义的错误信息而不是冻结窗口。 – 2014-09-13 08:05:47
不,没有错误,它并没有被冻结,它只是不响应x按钮点击,因此不保存文件的任何内容。 – betaFlux 2014-09-13 08:08:00