Reputation: 31
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.
Upvotes: 0
Views: 265
Reputation: 59633
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).
Upvotes: 2
Reputation: 152624
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();
}
}
Upvotes: 4