【发布时间】:2014-09-13 08:00:51
【问题描述】:
我有一个奇怪的问题。我想将可见的 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 文件中搜索“用户名 =”并返回紧随其后的文本。
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 限制为一行的任何提示?非常感谢!
【问题讨论】:
-
你确定它没有抛出异常吗?例如,您似乎正在尝试保存到文件夹而不是文件?
-
我在你的文件名中没有看到扩展名。顺便说一句,看看 try / catch。然后也许你会得到有意义的错误消息而不是冻结窗口。
-
不,完全没有错误,它没有被冻结,它只是对单击 x 按钮没有反应,因此不会保存任何文件。
-
尝试将新替换的内容存储在单独的字符串中,因为字符串是不可变的。通过您当前的编码替换的内容不会反映在新文件中。
-
我尝试改用 StreamWriter,但它也不起作用,因为“streamWriter.Write(path)”行。我真的不知道该怎么办。
标签: c# formclosing writealltext