奇妙な問題があります。表示されている 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);
}
フォームは問題なく起動しますが、×ボタンで終了しません。File.WriteAllText 行をコメントアウトした場合にのみ、正しく閉じます。デバッグを停止しただけでは、ファイルの内容も変わりません。
編集 :
実際の問題は、ini ファイルから userName を見つけて返すために使用した関数でした。
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」を捉えてくれたので、うまくいくと確信しました。ここで、ini ファイルで 'User Name =' を検索し、その直後のテキストを返す別の関数 (これも stackoverflow から) を使用します。
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 Name = SomeName
string result
1行だけに制限する方法に関するヒントはありますか? よろしくお願いします!