Reputation: 13
This function doesn't work because another process is using it.
The function must read the file, do something with it's data and write the result to this file.
private void changeToolStripMenuItem_Click(object sender, EventArgs e)
{
LB2.Visible = true;
TB2.Visible = true;
SaveFileDialog save = new SaveFileDialog();
if (save.ShowDialog() == DialogResult.OK)
{
double maxlen;
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
Find(read, out maxlen);
while (read.BaseStream.Position < read.BaseStream.Length)
{
double A = read.ReadDouble();
if (A > 0)
{
read.BaseStream.Seek(-8, SeekOrigin.Current);
w.Write(Find(read, out maxlen));
}
else
w.Write(A);
}
read.BaseStream.Close();
w.BaseStream.Close();
}
}
Upvotes: 1
Views: 616
Reputation: 4683
Change it to:
var fs=new FileStream(save.FileName, FileMode.OpenOrCreate);
BinaryReader read=new BinaryReader(fs);
BinaryWriter w=new BinaryWriter(fs);
and remove:
w.BaseStream.Close();
Upvotes: 0
Reputation: 4072
I would do this to make sure your streams are getting closed
using( BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open)))
{
using( BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create)) )
{
// CODE HERE
}
}
It sounds like you're getting an exception and you're not closing your streams/readers/writers.
Upvotes: 2
Reputation: 13877
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
Same file. BinaryWriter
probably encounters the exception, though I'm not entirely sure because you haven't showed us. You need to close your BinaryReader
before you can do anything else with that file.
Upvotes: 2
Reputation: 44288
you seem to be opening the same file twice?
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
Upvotes: 2
Reputation: 31184
my psychic debugging sense says that it's the FILE that's in use
And you're getting the error because you didn't close your BinaryReader
before you created your BinaryWriter
instead of this
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
...
read.BaseStream.Close();
w.BaseStream.Close();
do this
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
...
read.BaseStream.Close();
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
...
w.BaseStream.Close();
Upvotes: 2