テキストファイルのC#からデータを保存する方法は?
-
21-12-2019 - |
質問
私はプログラミングに新しい困難に直面しています。私が生成しているデータ(WPF DataGrid
)をテキストファイルに保存したいと思います。
これは私が現在持っているものです:
MainWindow.xaml.cs:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string fileName = @"D:\projects\PersonInfos\Files\PersonInfos_Copy.txt";
PersonInfosTable.ConvertToTXTFile(fileName);
}
.
PERSIONINFOSTABLE.cs:
public void ConvertToTXTFile(string fileName)
{
StringBuilder sb = new StringBuilder();
System.Text.Encoding Output = null;
Output = System.Text.Encoding.Default;
foreach (PersonInfos personinfos in PersonInfoDetails)
{
if (PersonInfos.SelectCheckBox == true)
{
string line = String.Format("L§" + personinfos.FirstName + "§" + personinfos.LastName + "§");
sb.AppendLine(line);
StreamWriter file = new StreamWriter(fileName);
file.WriteLine(sb);
file.Close();
}
}
}
.
残念ながら、これはうまくいきません。PersonInfosDetails
はObservationCollections<T>
型であり、SelectCheckBox
はユーザーが選択したチェックボックスであり、ユーザーが保存したいファイルを示します。
どんなアイデアや提案ですか?私はあなたの助けにとても感謝し、あなたの時間のためにそんなに感謝します!
解決
SelectCheckboxプロパティとは何が明確ではありません。ただし、プログラムの書き込み部分をループの外側に移動する必要があります。ループ内には、StringBuilderインスタンスにすべての人物情報を追加するだけです。
public void ConvertToTXTFile(string fileName)
{
StringBuilder sb = new StringBuilder();
System.Text.Encoding Output = System.Text.Encoding.Default;
foreach (PersonInfos personinfos in PersonInfoDetails)
{
// Collect every personinfos selected in the stringbuilder
if (personinfos.SelectCheckBox == true)
{
string line = String.Format("L§" + personinfos.FirstName + "§" + personinfos.LastName + "§");
sb.AppendLine(line);
}
}
// Now write the content of the StringBuilder all together to the output file
File.WriteAllText(filename, sb.ToString())
}
. 他のヒント
試してみましたか??
また、SelectCheckBox
がPersonInfos
クラスの静的プロパティでない限り、指定したコードは機能しません。if
ステートメントを
if (personInfos.SelectCheckBox == true)
{
// ...
}
. 所属していません StackOverflow