3

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!

Alessio Raddi
  • 540
  • 1
  • 6
  • 20
  • 1
    you can serialize them. check these two links : https://stackoverflow.com/questions/16352879/write-list-of-objects-to-a-file https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file – Farshad Jun 05 '17 at 09:07
  • _"Overriding the ToString() method worked fine. Thank you all for the answers!"_ - you should accept the answer then – FakeCaleb Jun 05 '17 at 09:31
  • Yes, sorry! I was trying every piece of code people gave me. – Alessio Raddi Jun 05 '17 at 09:34

11 Answers11

5

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()));
        }
    }
}
pitersmx
  • 935
  • 8
  • 27
4

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);
    }
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • 1
    @the Down-voter: please specify the reason so that I improve the post. if it's personal then need not to specify the reason, accepting it as a challenge. – sujith karivelil Jun 05 '17 at 09:23
2

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

Aedvald Tseh
  • 1,757
  • 16
  • 31
1

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

public class Dish
{
   // rest of code..


   public override string ToString() 
   {
      return Cost.ToString() + " " + Name;
   }
}
adjan
  • 13,371
  • 2
  • 31
  • 48
1

You need to use the attributes, so something like:

foreach (var item in Data.List)
{
    tw.WriteLine(item.Cost.ToString() + " " + item.Name);
}
Tom Bowen
  • 8,214
  • 4
  • 22
  • 42
1

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));
        }
    }
}
Nino
  • 6,931
  • 2
  • 27
  • 42
1

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

public override string ToString()
{
    return string.Format("Name: {0}, Cost: {1}",Name,Cost);
}
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
1

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")}"; 
    }
}
daniell89
  • 1,832
  • 16
  • 28
1

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;
    }
}
Markus
  • 66
  • 4
1

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}"));
   }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

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