none
How to write struct to text file in C#?

    Question

  • Hi,

    I am having challenge writing strings from struct to a text file.  Below is a partial snippet from my program.  I want to write the CS struct string data to a file but it is writing the namespace.customer instead.  How can I write the data to the file to make a single row or record?  Could you point me to the right direction?  Thanks in advance!


    struct Customer
     {
         public string FirstName;
         public string LastName;
         public string Address;
         public string City;
         public string State;
         public string Phone;
         public string email;
     }
     
     
    My C# Program snippet:
     
      Customer CS = new Customer();
                                    CS.FirstName = "John"; 
                                    CS.LastName = "Smith"; 
                                    CS.Address = "100 Boardway";
                                    CS.City = "New York"; 
                                    CS.State = "New York"; 
                                    CS.phone = "888-555-1212";
                                    CS.email = "John.Smith@gmail.com";
                                    
                                    outfile.WriteLine(CS.Tostring());   // It does not write above data to the text file.....
                             
                             


    Sunday, May 08, 2016 4:07 PM

Answers

  • >I am having challenge writing strings from struct to a text file.  Below is a partial snippet from my program.  I want to write the CS struct string data to a file but it is writing the namespace.customer instead.  How can I write the data to the file to make a single row or record?  Could you point me to the right direction?  Thanks in advance!

    You need to write a ToString override for your class that formats the
    members into a single string. See:
    https://msdn.microsoft.com/en-us/library/ms173154.aspx

    Dave

    • Marked as answer by Brandon.Ho Sunday, May 08, 2016 4:30 PM
    Sunday, May 08, 2016 4:15 PM

All replies

  • >I am having challenge writing strings from struct to a text file.  Below is a partial snippet from my program.  I want to write the CS struct string data to a file but it is writing the namespace.customer instead.  How can I write the data to the file to make a single row or record?  Could you point me to the right direction?  Thanks in advance!

    You need to write a ToString override for your class that formats the
    members into a single string. See:
    https://msdn.microsoft.com/en-us/library/ms173154.aspx

    Dave

    • Marked as answer by Brandon.Ho Sunday, May 08, 2016 4:30 PM
    Sunday, May 08, 2016 4:15 PM
  • Thanks for the fast response!  It works!
    • Marked as answer by Brandon.Ho Sunday, May 08, 2016 4:30 PM
    • Unmarked as answer by Brandon.Ho Sunday, May 08, 2016 4:31 PM
    Sunday, May 08, 2016 4:30 PM