Alessio Raddi
Alessio Raddi

Reputation: 622

Write list of objects to text file

I've got a class Dish like this:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}

In the main form the user can enter the previous data. Then I create a list of "Dish":

public static List<Piatto> List = new List<Piatto>();

I created it in a static class, so I can access it from anywhere. As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

Upvotes: 4

Views: 33780

Answers (11)

Maghalakshmi Saravana
Maghalakshmi Saravana

Reputation: 813

Try this:

Steps:

1.Get the list of Item in the Candidate Class object

2.Pass the list of Candidate in the Save method

3.Write the content in the Text files**

    public class Candidate
    {
      public string Name{get;set;}
      public string Department{get;set;}
    }        
    public void save(List<Candidate>iolist)
    {          
     var dir = @"D:\New folder\log";
     string path = System.IO.Path.Combine(dir, "items1213.txt");
     File.WriteAllLines(path, iolist.Select(o => o.Name + " " + o.Department));    
    }

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

When converting Dish instance into String, .Net uses ToString() method which default (i.e. Object.ToString()) implementation returns item's type name:

   WindowsFormsApplication1.Dish

you can either provide your version of ToString:

   public class Dish 
   {
     ...

       public override string ToString() 
       {
           return $"{Cost} {Name}";         
       }
   }

Or put the right format in the very place you write it into the file (with a little help of Linq - Select):

   public static void SaveToTxt() {
     // File class allows to get rid of pesky readers and writers
     File.WriteAllLines(Path, Data.List.Select(dish => $"{dish.Cost} {dish.Name}"));
   }

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29006

Its simple, You are almost there, I think you forgot to override the .ToString() method inside your class. By overriding the .ToString() method you can return the string representation of its object. You can format them as well. So you have to add this overrided .ToString() method to make it work. Consider the following code

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
    public override string ToString() 
    {
       return String.Format("Item Name :{0} \n Item Cost : {1}", this.Name,this.Cost);
    }
}

Upvotes: 4

Markus
Markus

Reputation: 66

If you just want to write, the quickest way without too many code changes is to override your ToString method.

public class Dish
{
    public Dish(int cost, string name)
    {
       Cost = cost;
       Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }

    public override string ToString(){
        return "Name: "+Name+" cost: "+cost;
    }
}

Upvotes: 1

pitersmx
pitersmx

Reputation: 957

your item is an object that contains several properties and you have to access them:

public static void SaveToTxt()
{
    using (TextWriter tw = new StreamWriter(Path))
    {
        foreach (var item in Data.List)
        {
            tw.WriteLine(string.Format("Item: {0} - Cost: {1}", item.Name, item.Cost.ToString()));
        }
    }
}

Upvotes: 6

Aedvald Tseh
Aedvald Tseh

Reputation: 1917

Consider using XmlSerializer to write content of your object to an XML-file.

https://support.microsoft.com/en-us/help/815813/how-to-serialize-an-object-to-xml-by-using-visual-c

Upvotes: 2

daniell89
daniell89

Reputation: 2272

I think you have to override ToString method in your Dish class:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return $"{Name}: {Cost.ToString("c")}"; 
    }
}

Upvotes: 1

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

You need to override ToString method of your class like this:

public override string ToString()
{
    return string.Format("Name: {0}, Cost: {1}",Name,Cost);
}

Upvotes: 1

Nino
Nino

Reputation: 7095

Change your code to something like this

public static void SaveToTxt()
{
    using (TextWriter tw = new StreamWriter(Path))
    {
        foreach (var item in Data.List)
        {
            tw.WriteLine(string.Format("{0} {1}", item.Name, item.Cost));
        }
    }
}

Upvotes: 1

Tom Bowen
Tom Bowen

Reputation: 8514

You need to use the attributes, so something like:

foreach (var item in Data.List)
{
    tw.WriteLine(item.Cost.ToString() + " " + item.Name);
}

Upvotes: 1

adjan
adjan

Reputation: 13652

Override the ToString() method in Dish. For example:

public class Dish
{
   // rest of code..


   public override string ToString() 
   {
      return Cost.ToString() + " " + Name;
   }
}

Upvotes: 1

Related Questions