Reputation: 51
I am trying to write my list to a txt file. But instead of adding the properties of my list object items. Like just Animal.Name, Animal.Number etc. It also adds the ToString() text in front of each property.
How do I prevent this from happening? I know I can do txt.Write(animal.Name, animal.Number etc.) but can't I simply exclude the ToString values?
public void Save(string fileName)
{
Txt = new StreamWriter(@"path" + fileName);
foreach(Animal animals in Animals)
{
Txt.Write(animals + "\n");
}
Txt.Close();
}
This is my ToString():
public override ToString()
{
string info = "Animal ID: " + ChipRegistrationNumber
+ "\nAnimal Birthdate: " + DateOfBirth
+ "\nAnimal Name: " + Name
+ "\nAnimal Status: " + IsReservedString
+ "\nAnimal Gender: " + Gender;
return info;
}
The current output in my textfile is:
Animal ID: 0
Animal Birthdate: 10-12-1999
Animal Name: Snoopy
Animal Status: Not reserved
Animal Gender: Male
Days since last walk: 34
Dog Price: €200,00
So I just want the object data from the list not the ToString.
Upvotes: 1
Views: 717
Reputation: 8743
You can add another method ToShortString()
:
public string ToShortString()
{
string info = ChipRegistrationNumber + DateOfBirth + Name + IsReservedString + Gender;
return info;
}
Then you can call this method in your loop:
foreach(Animal animals in Animals)
{
Txt.Write(animals.ToShortString() + "\n");
}
If your properties of your Animal
class change often, you can also use reflection. But this will decrease your performance.
public string ToShortString()
{
PropertyInfo[] properties = GetType().GetProperties();
StringBuilder result = new StringBuilder();
foreach(var prop in properties)
{
result.Append(prop.GetValue(this));
}
return result.ToString();
}
Upvotes: 1