Dispensable Joe
Dispensable Joe

Reputation: 74

Saving a List of Objects to Txt File

Ok so I thought I could have achieved this one easily but it is now clear I'm missing something big.

I have a Class named Oggetto, Oggetto has a public string Nome {get;set;} and a public string Descrizione {get;set;}

These are Binded to a TextBox in a Cell of a DataGrid like this

<DataGridTemplateColumn Header="Nome" MinWidth="60">
                                    <DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate DataType="{x:Type local:Oggetto}">
                                            <TextBox Text="{Binding Nome}"/>
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
                                </DataGridTemplateColumn>
                                <DataGridTemplateColumn Header="Descrizione" MinWidth="100">
                                    <DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate DataType="{x:Type local:Oggetto}">
                                            <TextBox Text="{Binding Descrizione}" TextWrapping="Wrap" />
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
                                </DataGridTemplateColumn>

Upon the clicking of a button I add an empty object to the List of Oggetto I have previously declared like this

List<Oggetto> oggetti = new List<Oggetto>();

the adding method does this

private void btn_AggOgg_Click(object sender, RoutedEventArgs e)
    {
        oggetti.Add(new Oggetto() { });

        dg_Misc.ItemsSource = oggetti;
        dg_Misc.Items.Refresh();

        dg_Misc.Columns[1].Width = new DataGridLength(1, DataGridLengthUnitType.Star);
        dg_Misc.CanUserResizeRows = false;
    }

I also have a saving method which does this upon the clicking of another button

public void Salvataggio()
    {
        StreamWriter sw = new StreamWriter("MiscSave");

        foreach(Oggetto oggetto in oggetti)
        {
            sw.WriteLine(oggetti);
        }

        sw.Close();
    }

And my problem is the File MiscSave.txt is all completely blank. I've tried several solutions I found here and there but I can't seem to make them work for me.

For example I don't even know if Binding the oggetto.Descrizione to the TextBlock actually makes it change when what is written inside changes. I thought about something like

oggetto.Nome = oggetti[0].Text

but even in my head it doesn't make a lot of sense.

I also don't speak english as my primary language so sorry in advance for any mistake I made, feel free to point them out, but mostly feel free to point out the holes in my comprehension of saving a list to a txt file.

Upvotes: 1

Views: 2007

Answers (4)

Mark Feldman
Mark Feldman

Reputation: 16119

I agree with Theo i.e. use serialization if you can. Otherwise just do something like this:

File.WriteAllLines("MiscSave", oggetti.Select(o => 
            o.Nome + " " + o.Descrizione
        ));

Upvotes: 1

Again, i would recommend doing this via xml or serialization or something. This would help when you want to read back the file. However, try this method: File.WriteAllLines

Here's the MSDN link and example.
https://msdn.microsoft.com/en-us/library/dd383693%28v=vs.110%29.aspx You will need to supply the method a file path to save to and a collection of the strings you want to save. You may need to make another collection from your Ogetta or whatever or do a for loop for that collection and insert the string properties etc before you can pass it to the File.WriteAllText method.

Upvotes: 2

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

You can also try using DataContractSerializer to serialize the type. Following code should serialize the object to a file.

 FileStream writer = new FileStream(fileName, FileMode.Create);
 DataContractSerializer ser = new DataContractSerializer(typeof(List<Oggetto>));
 ser.WriteObject(writer, oggetti);
 writer.Close();

Upvotes: 1

Stewbob
Stewbob

Reputation: 16899

In your Save method:

sw.WriteLine(oggetti);

you are trying to save an entire list of custom objects of type Oggetto to a line in a text file.

That is not going to work because the WriteLine method needs a string as the parameter.

Something like: sw.WriteLine(oggetto.Nome); would probably work, as long as Nome is of type string.

That way you are accessing a string property of each item in your list of Oggetto objects. Not the entire collection (List) at one time.

Upvotes: 1

Related Questions