Can StreamWriter save an entire Class?

1.2k views Asked by At

I have created a class that requests user input (7 textboxes of individual data)

I need to save that data for later use in a flat file using the StreamWriter Class.

Do I have to create individual instances for each field?

private void btnSaveFile_Click(object sender, EventArgs e) { StreamWriter studentInfo = new StreamWriter(txtFirstName.Text); }

or is there a way I can ask StreamWriter to print all the fields in that class? I tried overloading the method, however apparently that can't be done.

2

There are 2 answers

8
David Espino On

Yes, if you serialize it as JSON or XML first, get it as string... or the simplest way... add a ToString() Method to your class:

    class Person
    {
            public string Name { get; set; }
            public int Age { get; set; }
            public Person (string name, int age) {
              this.Name = name;
              this.Age = age;
            }
            public override string ToString()
            {
                return "Person: " + Name + " " + Age;

            }

     }

And then write your Class instance to write it to a file:

private void btnSaveFile_Click(object sender, EventArgs e)
{
   string mydocpath = ""; // add your path here
   Person newPerson =  new Person ("David", 32);
   using (StreamWriter studentInfo = new StreamWriter(mydocpath + @"\Student.txt")) {
      studentInfo.WriteLine(newPerson.ToString());
   }
}

Hope this helps

0
Sefe On

You can mark your class with the [Serializable] attribute. You can then use a BinaryFormatter to write the class to the stream. That is if it doesn't matter to you if the data is human readable.