0

I am trying to write and read binary file in a WinForm. I thought that I did it but when I try to read the file, I only get the new number that was written to the file (random numbers generated every 5 seconds), that file does not retain the previous figures. what i did:

private void timer1_Tick(object sender, EventArgs e)
        {
            string path = @"C:\Test\test.dat";
            lbl1.Text = string.Format("{0:0.0}", -6 + rand.NextDouble() * 17);
            double temp = Convert.ToDouble(lbl1.Text);
            try
            {
                  if (!File.Exists(path))
                  {
                    lock (sync)
                    {
                      FileStream outf = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
                      BinaryWriter bw = new BinaryWriter(outf);
                      bw.Write(temp);
                      bw.Close();
                    }
                  }
                  else if (File.Exists(path))
                  {
                    lock (synk)
                    {
                       FileStream outf1 = new FileStream(path, FileMode.Create, FileAccess.Write);
                       BinaryWriter bw1 = new BinaryWriter(outf1);
                       bw1.Write(temp);
                       bw1.Flush();
                       bw1.Close();
                    }
                  }
                }
            catch (System.IO.FileNotFoundException ioe)
            {
              MessageBox.Show(ioe.Message);
            }

What am I doing wrong? Is there anyone who can help me? Thanks in advance.

2 Answers 2

4

You are opening the stream using FileMode.Create, which overwrites the existing file. Use FileMode.Append instead.

Note that you don't have to check to see if the file exists or not; you can use FileMode.OpenOrCreate | FileMode.Append to create it if it doesn't exist:

try
{
    lock (sync)
    {
       FileStream outf = new FileStream(path, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write);
       BinaryWriter bw = new BinaryWriter(outf);
       bw.Write(temp);
       bw.Flush();
       bw.Close();
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why the flush-method?
I am getting the same result. Constantly just the latest number.
@Steve because it was in the original code. I just removed the extraneous if block.
@Steve, are you sure you copied the example code correctly? I have taken your code and combined it with the code in this answer and it is definitely appending new numbers to the end of the file. How are you confirming whether your code is working or not?
2

What you're doing wrong:

if (!File.Exists(path))
...
else if (File.Exists(path))
...

A simple else would have been enough.

However, not that exceptions can still happen if someone would create the file after the "not exists" check has already been performed or the file gets deletes after the "exists" check has been performed.


lock (sync)
...
lock (synk)

You are locking on different synchronization objects.

Other than that, the code will always be executed on the same thread (UI thread), since timer ticks are handled by Windows messages. This means, the lock statment can probably be omitted (if you don't have use threads explicitly somewhere else).


but when I try to read the file

Actually both code pieces are writing to the file.

bw.Write(temp);
...
bw1.Write(temp);

FileMode.Create (MSDN) overwrites existing files. FileMode.Open and FileAccess.Read would be better suited for reading.

Then, of course, use a BinaryReader (MSDN).

2 Comments

OpenOrCreate overwrites as well unless you combine it with Append.
@DStanley Thanks. I was focusing on the read part only, so I updated my answer to use FileMode.Open and FilAccess.Read. I'm not sure if he really wants to append or only have a single random number in the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.