Urim Sadiku
Urim Sadiku

Reputation: 3

How To save from my list in TextFile?

I need to save my List<Cupon> to a text file. I am using this code:

File.WriteAllText(@"C:\Users\urim.sadiku\Desktop\Loja.txt", Cupo.ToString());
List<string> myList = new List<string>(Cupo.ToString().Split(','));

but the output in txtFile is:

System.Collections.Generic.List`1[LojeShperblyese2.Coupon]

Note : I need to save with Split(), but I don't know how to do that.

What do I need to do to save my list correctly?

Upvotes: 0

Views: 119

Answers (3)

Uchiha_Sasuke
Uchiha_Sasuke

Reputation: 309

I should add that you should override ToString() Method of class Coupon to return your desired string that you want to be written to file, then Ilya Ivanov's answer will work.

Upvotes: 0

Ilya Ivanov
Ilya Ivanov

Reputation: 23626

By default, ToString method return type name, if it is not overriden in subclass.

Try to use

File.WriteAllText(@"C:\Users\urim.sadiku\Desktop\Loja.txt",
                 string.Join(",", Cupo));

This assumes, that you have implemented ToString method corrrectly on your LojeShperblyese2.Coupon class

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45083

ToString on List won't concatenate all elements of the list and return that, you'd need a custom implementation for such (or maybe there's an existing type that does behave like this, but not List).

Note the name of the method you're calling, particularly the Text part.

To correct your specific case, you'd need to define a string variable, and loop all elements of the list while building the output to write (youstring += item), then use File.WriteAllText(yourstring) - or some variation of this method, of which no doubt you could ask anyone on SO for a method to 'do it in one line?!'.

However, you could use File.WriteAllLines, which will do the same thing for you but with handling the iteration of each element for you.

Upvotes: 1

Related Questions