Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Text File

Text File

Scheduled Pinned Locked Moved C#
questioncsharpvisual-studiohelptutorial
16 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Morgs Morgan

    Hi people, I want to write to text file and read from it and here is my plan of how my student.txt file should look like(just a sample)... ****************************Student Entry******************************       First Name      Last Name   Age   Gender   Student No.   Mobile 1.   Morgan            Simwaba      21      Male      MB6709            074-372-**** 2.   Morgan            Freeman      11      Male      MB6709            084-372-**** 3.   Morgan            Morgan         99      Female   MB6709            074-372-**** ****************************Student Entry****************************** My question is how can I write the column headings(e.g First Name) and write required values(e.g Morgan) under each column heading as indicated above. Then I want to read from this file and retrieve the data under each column. I am using visual studio 8 and this far have tried to use the FileStream, StreamWriter, BufferedStream and StreamReader. I already know how to create a new file, write one line into a file and read that one line but I have failed the format above... Please Please Help ME:confused: :doh:

    OriginalGriffO Offline
    OriginalGriffO Offline
    OriginalGriff
    wrote on last edited by
    #2

    Have a look at string.format:

    String.Format("--{0,10}--", "test");
    prints as: -- test--
    String.Format("--{0,-10}--", "test");
    prints as: --test --

    No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones "Rumour has it that if you play Microsoft CDs backwards you will hear Satanic messages.Worse still, is that if you play them forwards they will install Windows"

    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

    M 1 Reply Last reply
    0
    • OriginalGriffO OriginalGriff

      Have a look at string.format:

      String.Format("--{0,10}--", "test");
      prints as: -- test--
      String.Format("--{0,-10}--", "test");
      prints as: --test --

      No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones "Rumour has it that if you play Microsoft CDs backwards you will hear Satanic messages.Worse still, is that if you play them forwards they will install Windows"

      M Offline
      M Offline
      Morgs Morgan
      wrote on last edited by
      #3

      Thankyou but that one won't do still, how am I going to write that to a text file. remember I have headings and data below the headings. Any other idea?:confused:

      T 1 Reply Last reply
      0
      • M Morgs Morgan

        Thankyou but that one won't do still, how am I going to write that to a text file. remember I have headings and data below the headings. Any other idea?:confused:

        T Offline
        T Offline
        The Man from U N C L E
        wrote on last edited by
        #4

        If the main purpose is storing this data for retrieval in your app I suggest saving it as XML rather than straight text. That way you can match up the records, fields and values easily.

        If you have knowledge, let others light their candles at it. Margaret Fuller (1810 - 1850) www.JacksonSoft.co.uk

        M 1 Reply Last reply
        0
        • T The Man from U N C L E

          If the main purpose is storing this data for retrieval in your app I suggest saving it as XML rather than straight text. That way you can match up the records, fields and values easily.

          If you have knowledge, let others light their candles at it. Margaret Fuller (1810 - 1850) www.JacksonSoft.co.uk

          M Offline
          M Offline
          Morgs Morgan
          wrote on last edited by
          #5

          Nice one! Can you help me by showing me how to do that?

          N 1 Reply Last reply
          0
          • M Morgs Morgan

            Hi people, I want to write to text file and read from it and here is my plan of how my student.txt file should look like(just a sample)... ****************************Student Entry******************************       First Name      Last Name   Age   Gender   Student No.   Mobile 1.   Morgan            Simwaba      21      Male      MB6709            074-372-**** 2.   Morgan            Freeman      11      Male      MB6709            084-372-**** 3.   Morgan            Morgan         99      Female   MB6709            074-372-**** ****************************Student Entry****************************** My question is how can I write the column headings(e.g First Name) and write required values(e.g Morgan) under each column heading as indicated above. Then I want to read from this file and retrieve the data under each column. I am using visual studio 8 and this far have tried to use the FileStream, StreamWriter, BufferedStream and StreamReader. I already know how to create a new file, write one line into a file and read that one line but I have failed the format above... Please Please Help ME:confused: :doh:

            X Offline
            X Offline
            Xelalem
            wrote on last edited by
            #6

            for example if you want to save the data from textboxes you can use this sample function...... of course you have to modify it .. private void Save()         { string sample=   "******Student Entry**** \r\n First Name   Last Name   Age   Gender Student No.   Mobile";          sample+= "\r\n*"+textBox1.Text+"   "+"#"+textBox2.Text+"   "+"@"+textBox3.Text+"   "+"%"+textBox4.Text; File.WriteAllText("d:\\sample\\data.txt",sample); } Dont forget to include the System.IO namespace... You can use the tags i included(*,@,# ...) to retrive the data from each column....

            1 Reply Last reply
            0
            • M Morgs Morgan

              Hi people, I want to write to text file and read from it and here is my plan of how my student.txt file should look like(just a sample)... ****************************Student Entry******************************       First Name      Last Name   Age   Gender   Student No.   Mobile 1.   Morgan            Simwaba      21      Male      MB6709            074-372-**** 2.   Morgan            Freeman      11      Male      MB6709            084-372-**** 3.   Morgan            Morgan         99      Female   MB6709            074-372-**** ****************************Student Entry****************************** My question is how can I write the column headings(e.g First Name) and write required values(e.g Morgan) under each column heading as indicated above. Then I want to read from this file and retrieve the data under each column. I am using visual studio 8 and this far have tried to use the FileStream, StreamWriter, BufferedStream and StreamReader. I already know how to create a new file, write one line into a file and read that one line but I have failed the format above... Please Please Help ME:confused: :doh:

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #7

              XML is ideal, but you're already half way there. Use a "delimited" file format (for starters), with the first row containing "headings" and the other rows "data", and each field separated by a "special" character (in this case "|"). This is a very common method used by various applications / databases to import / export data. Since you already know how to read a line using StreamReader, use the string.Split() method to then split these lines on the "|" character to get an array of column names and subsequent data values in the corresponding columns. (Your data in delimited format)

              First Name|Last Name|Age|Gender|Student No.|Mobile
              Morgan|Simwaba|21|Male|MB6709|074-372-****

              etc

              1 Reply Last reply
              0
              • M Morgs Morgan

                Hi people, I want to write to text file and read from it and here is my plan of how my student.txt file should look like(just a sample)... ****************************Student Entry******************************       First Name      Last Name   Age   Gender   Student No.   Mobile 1.   Morgan            Simwaba      21      Male      MB6709            074-372-**** 2.   Morgan            Freeman      11      Male      MB6709            084-372-**** 3.   Morgan            Morgan         99      Female   MB6709            074-372-**** ****************************Student Entry****************************** My question is how can I write the column headings(e.g First Name) and write required values(e.g Morgan) under each column heading as indicated above. Then I want to read from this file and retrieve the data under each column. I am using visual studio 8 and this far have tried to use the FileStream, StreamWriter, BufferedStream and StreamReader. I already know how to create a new file, write one line into a file and read that one line but I have failed the format above... Please Please Help ME:confused: :doh:

                A Offline
                A Offline
                Abhishek Sur
                wrote on last edited by
                #8

                Why do you want text file to store data.. Rather use XML to do this. XML is easier to manage and Data integration remains intact. So it is lesser possibility of data corruption in case of XML files.

                Abhishek Sur **Don't forget to click "Good Answer" if you like this Solution.


                My Latest Articles-->** Simplify Code Using NDepend
                Basics of Bing Search API using .NET
                Microsoft Bing MAP using Javascript

                1 Reply Last reply
                0
                • M Morgs Morgan

                  Hi people, I want to write to text file and read from it and here is my plan of how my student.txt file should look like(just a sample)... ****************************Student Entry******************************       First Name      Last Name   Age   Gender   Student No.   Mobile 1.   Morgan            Simwaba      21      Male      MB6709            074-372-**** 2.   Morgan            Freeman      11      Male      MB6709            084-372-**** 3.   Morgan            Morgan         99      Female   MB6709            074-372-**** ****************************Student Entry****************************** My question is how can I write the column headings(e.g First Name) and write required values(e.g Morgan) under each column heading as indicated above. Then I want to read from this file and retrieve the data under each column. I am using visual studio 8 and this far have tried to use the FileStream, StreamWriter, BufferedStream and StreamReader. I already know how to create a new file, write one line into a file and read that one line but I have failed the format above... Please Please Help ME:confused: :doh:

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #9

                  Yeah, XML. I suggest you use an XmlDocument.

                  1 Reply Last reply
                  0
                  • M Morgs Morgan

                    Nice one! Can you help me by showing me how to do that?

                    N Offline
                    N Offline
                    N a v a n e e t h
                    wrote on last edited by
                    #10

                    Use XML serialization. You need to define a type that has all the required columns.

                    public class Student
                    {
                    public string FirstName { get; set; }
                    public string LastName { get; set; }
                    public int Age { get; set; }
                    public string Gender { get; set; }
                    public int StudentNo { get; set; }
                    public int Mobile { get; set; }
                    }

                    Use the XmlSerializer class provided in the System.Xml.Serialization namespace to serialize and deserialize the object.

                    void Serialize(string file, List<Student> students)
                    {
                    XmlSerializer xs = new XmlSerializer(students.GetType());
                    using (FileStream fs = new FileStream(file, FileMode.Create))
                    {
                    xs.Serialize(fs, students);
                    }
                    }

                    List<Student> Deserialize(string file)
                    {
                    XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
                    object obj = null;
                    using (FileStream fs = new FileStream(file, FileMode.Open))
                    {
                    obj = xs.Deserialize(fs);
                    }
                    return (List<Student>)obj;
                    }

                    Use this like

                    Student student1 = new Student();
                    student1.FirstName = "First";
                    student1.LastName = "Student";
                    Student student2 = new Student();
                    student2.FirstName = "Second";
                    student2.LastName = "Student";
                    // set required properties of student

                    List<Student> students = new List<Student>();
                    students.Add(student1);
                    students.Add(student2);

                    // Write to file
                    Serialize("c:\\some.xml", students);

                    use Deserialize with the file name to get the students back. :)

                    Best wishes, Navaneeth

                    M P 3 Replies Last reply
                    0
                    • M Morgs Morgan

                      Hi people, I want to write to text file and read from it and here is my plan of how my student.txt file should look like(just a sample)... ****************************Student Entry******************************       First Name      Last Name   Age   Gender   Student No.   Mobile 1.   Morgan            Simwaba      21      Male      MB6709            074-372-**** 2.   Morgan            Freeman      11      Male      MB6709            084-372-**** 3.   Morgan            Morgan         99      Female   MB6709            074-372-**** ****************************Student Entry****************************** My question is how can I write the column headings(e.g First Name) and write required values(e.g Morgan) under each column heading as indicated above. Then I want to read from this file and retrieve the data under each column. I am using visual studio 8 and this far have tried to use the FileStream, StreamWriter, BufferedStream and StreamReader. I already know how to create a new file, write one line into a file and read that one line but I have failed the format above... Please Please Help ME:confused: :doh:

                      H Offline
                      H Offline
                      hosseinghazanfary
                      wrote on last edited by
                      #11

                      if i were u and i had data like that one u brought as an example,i would simply make an access mdb file with one table with columns of Fname,Lname,... and insert and select from that file using jet 4.0 or Oledb 12,it's much easier,but the solution is our friend gave us about xml serializing is also very easy and comforting. u can select from an oledb database like this. oledbcommand oc=new oledbcommand (); oledbconnection ocon=new oledbconnection(connectionstring); oc.connection=ocon; oc.commandtext="select *from studenttable"; oledbdatareader dr=oc.executeReader();

                      M 1 Reply Last reply
                      0
                      • N N a v a n e e t h

                        Use XML serialization. You need to define a type that has all the required columns.

                        public class Student
                        {
                        public string FirstName { get; set; }
                        public string LastName { get; set; }
                        public int Age { get; set; }
                        public string Gender { get; set; }
                        public int StudentNo { get; set; }
                        public int Mobile { get; set; }
                        }

                        Use the XmlSerializer class provided in the System.Xml.Serialization namespace to serialize and deserialize the object.

                        void Serialize(string file, List<Student> students)
                        {
                        XmlSerializer xs = new XmlSerializer(students.GetType());
                        using (FileStream fs = new FileStream(file, FileMode.Create))
                        {
                        xs.Serialize(fs, students);
                        }
                        }

                        List<Student> Deserialize(string file)
                        {
                        XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
                        object obj = null;
                        using (FileStream fs = new FileStream(file, FileMode.Open))
                        {
                        obj = xs.Deserialize(fs);
                        }
                        return (List<Student>)obj;
                        }

                        Use this like

                        Student student1 = new Student();
                        student1.FirstName = "First";
                        student1.LastName = "Student";
                        Student student2 = new Student();
                        student2.FirstName = "Second";
                        student2.LastName = "Student";
                        // set required properties of student

                        List<Student> students = new List<Student>();
                        students.Add(student1);
                        students.Add(student2);

                        // Write to file
                        Serialize("c:\\some.xml", students);

                        use Deserialize with the file name to get the students back. :)

                        Best wishes, Navaneeth

                        M Offline
                        M Offline
                        Morgs Morgan
                        wrote on last edited by
                        #12

                        thank you very much that was helpful

                        1 Reply Last reply
                        0
                        • N N a v a n e e t h

                          Use XML serialization. You need to define a type that has all the required columns.

                          public class Student
                          {
                          public string FirstName { get; set; }
                          public string LastName { get; set; }
                          public int Age { get; set; }
                          public string Gender { get; set; }
                          public int StudentNo { get; set; }
                          public int Mobile { get; set; }
                          }

                          Use the XmlSerializer class provided in the System.Xml.Serialization namespace to serialize and deserialize the object.

                          void Serialize(string file, List<Student> students)
                          {
                          XmlSerializer xs = new XmlSerializer(students.GetType());
                          using (FileStream fs = new FileStream(file, FileMode.Create))
                          {
                          xs.Serialize(fs, students);
                          }
                          }

                          List<Student> Deserialize(string file)
                          {
                          XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
                          object obj = null;
                          using (FileStream fs = new FileStream(file, FileMode.Open))
                          {
                          obj = xs.Deserialize(fs);
                          }
                          return (List<Student>)obj;
                          }

                          Use this like

                          Student student1 = new Student();
                          student1.FirstName = "First";
                          student1.LastName = "Student";
                          Student student2 = new Student();
                          student2.FirstName = "Second";
                          student2.LastName = "Student";
                          // set required properties of student

                          List<Student> students = new List<Student>();
                          students.Add(student1);
                          students.Add(student2);

                          // Write to file
                          Serialize("c:\\some.xml", students);

                          use Deserialize with the file name to get the students back. :)

                          Best wishes, Navaneeth

                          P Offline
                          P Offline
                          PIEBALDconsult
                          wrote on last edited by
                          #13

                          Serialization was designed for other purposes; I wouldn't use it just to create a file.

                          N 1 Reply Last reply
                          0
                          • H hosseinghazanfary

                            if i were u and i had data like that one u brought as an example,i would simply make an access mdb file with one table with columns of Fname,Lname,... and insert and select from that file using jet 4.0 or Oledb 12,it's much easier,but the solution is our friend gave us about xml serializing is also very easy and comforting. u can select from an oledb database like this. oledbcommand oc=new oledbcommand (); oledbconnection ocon=new oledbconnection(connectionstring); oc.connection=ocon; oc.commandtext="select *from studenttable"; oledbdatareader dr=oc.executeReader();

                            M Offline
                            M Offline
                            Morgs Morgan
                            wrote on last edited by
                            #14

                            Thank you my friend though I already know that one! I have been using SQL 2005 and all is well, I thought it would be much easier to use a file than a database - remember I can carry a file to anywhere but I can't use a database anywhere else but only on a computer that has SQL. Well, thanks to you all guys out there you are alot of help and I will dig through XML again and again! LaTa......

                            1 Reply Last reply
                            0
                            • P PIEBALDconsult

                              Serialization was designed for other purposes; I wouldn't use it just to create a file.

                              N Offline
                              N Offline
                              N a v a n e e t h
                              wrote on last edited by
                              #15

                              PIEBALDconsult wrote:

                              Serialization was designed for other purposes;

                              What are those?

                              Best wishes, Navaneeth

                              1 Reply Last reply
                              0
                              • N N a v a n e e t h

                                Use XML serialization. You need to define a type that has all the required columns.

                                public class Student
                                {
                                public string FirstName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Gender { get; set; }
                                public int StudentNo { get; set; }
                                public int Mobile { get; set; }
                                }

                                Use the XmlSerializer class provided in the System.Xml.Serialization namespace to serialize and deserialize the object.

                                void Serialize(string file, List<Student> students)
                                {
                                XmlSerializer xs = new XmlSerializer(students.GetType());
                                using (FileStream fs = new FileStream(file, FileMode.Create))
                                {
                                xs.Serialize(fs, students);
                                }
                                }

                                List<Student> Deserialize(string file)
                                {
                                XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
                                object obj = null;
                                using (FileStream fs = new FileStream(file, FileMode.Open))
                                {
                                obj = xs.Deserialize(fs);
                                }
                                return (List<Student>)obj;
                                }

                                Use this like

                                Student student1 = new Student();
                                student1.FirstName = "First";
                                student1.LastName = "Student";
                                Student student2 = new Student();
                                student2.FirstName = "Second";
                                student2.LastName = "Student";
                                // set required properties of student

                                List<Student> students = new List<Student>();
                                students.Add(student1);
                                students.Add(student2);

                                // Write to file
                                Serialize("c:\\some.xml", students);

                                use Deserialize with the file name to get the students back. :)

                                Best wishes, Navaneeth

                                M Offline
                                M Offline
                                Morgs Morgan
                                wrote on last edited by
                                #16

                                Hai, I tried the code you gave me and it did work very well, thanks. but I have a problem with deserialization, it returns a List<Student>obj and am not sure how to get around with this to see the items that are returned. Can you please help me? :doh:

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups