Save and Load text and integer data in same file.

steve_ancell

New member
Joined
Oct 22, 2017
Messages
2
Programming Experience
10+
Hello, I'm Steve, and I'm new here.

In the code below: the Save function is intended to save out a line of text and then followed by a series of integers, it saves the text last; this is the opposite to what I want. The load function just loads the text back in an undesirable way, followed by a load of -1.

Can anybody please tell me what I'm doing wrong? :-/

C#:
public void Save(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            BinaryWriter bw = new BinaryWriter(fs);

            sw.WriteLine("Text Line: This should be the first line.");

            for (int i = 0; i < 10; i++)
            {
                bw.Write(i);

            }

            sw.Close();
            bw.Close();
            fs.Close();
            
        }

        public void Load(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            BinaryReader br = new BinaryReader(fs);

            Console.WriteLine(sr.ReadLine());

            for(int i = 0; i < 10; i++)
            {
                Console.WriteLine(br.Read());

            }

            sr.Close();
            br.Close();
            fs.Close();

        }
 
Don't create a StreamWriter and a BinaryWriter. The BinaryWriter can write both numbers and text so use it for everything. Similarly, use a BinaryReader to read everything.
 
This will do exactly what you want:

C#:
FileStream fs = new FileStream(fileName, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Text Line: This should be the first line.");
for (int i = 0; i < 10; i++)
{
    sw.WriteLine(i);
}
sw.Close();
fs.Close();
 

Attachments

  • 2017-10-23_090258.png
    2017-10-23_090258.png
    236.1 KB · Views: 50
Back
Top Bottom