我有一个奇怪的问题。我想将可见的 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
为一行的任何提示?提前谢谢了!