Question

I'm new to programming and face some difficulties. I hope to save the data I'm generating (a WPF DataGrid) into a text file.

This is what I currently have:

MainWindow.xaml.cs:

private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    string fileName = @"D:\projects\PersonInfos\Files\PersonInfos_Copy.txt";
    PersonInfosTable.ConvertToTXTFile(fileName);
}

PersonInfosTable.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();
        }
    }
}

Unfortunately, this doesn't work. PersonInfosDetails is of type ObservationCollections<T> and SelectCheckBox is the check box selected by the user, and indicates which files the user wants to save.

Any ideas or suggestions? I'd appreciate your help so much and thank you so much for your time!

Was it helpful?

Solution

It is not clear what is the SelectCheckBox property. However, you need to move the writing part of your program outside the loop. Inside the loop just add every person info to your StringBuilder instance.

 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())
}

OTHER TIPS

Have you tried How to: Write to a Text File (C# Programming Guide)?

Also, the code you've supplied won't work unless SelectCheckBox is a static property of the PersonInfos class. You'll probably have to change the if statement to

if (personInfos.SelectCheckBox == true)
{
    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top