1

此功能不起作用,因为另一个进程正在使用它。

该函数必须读取文件,对其数据进行处理并将结果写入该文件。

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();
            }
        }
4

5 回答 5

2

我的心理调试感觉说这是正在使用的文件

而且您收到错误是因为您BinaryReader在创建之前没有关闭您的BinaryWriter


而不是这个

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();

做这个

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();
于 2013-04-25T20:53:34.567 回答
2

你似乎打开同一个文件两次?

 BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
 BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
于 2013-04-25T20:53:44.990 回答
2
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));

同一个文件。BinaryWriter可能会遇到异常,尽管我不完全确定,因为您没有向我们展示。您需要先关闭您的BinaryReader文件,然后才能对该文件执行任何其他操作。

于 2013-04-25T20:54:55.973 回答
2

我会这样做以确保您的流已关闭

using( BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open)))
{
   using( BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create)) )
   {
       // CODE HERE
   }
}

听起来您遇到了异常,并且没有关闭流/读取器/写入器。

于 2013-04-25T21:04:09.077 回答
0

将其更改为:

var fs=new FileStream(save.FileName, FileMode.OpenOrCreate);
BinaryReader read=new BinaryReader(fs);
BinaryWriter w=new BinaryWriter(fs);

并删除:

w.BaseStream.Close();
于 2013-04-25T21:08:02.740 回答