循环中的BinaryWriter导致“文件被另一个进程使用”错误,即使它已关闭并且“正在使用”

时间:2012-06-28 15:36:19

标签: c#

标题就是真的。

private bool addToBinary(byte[] msg, string filepath)
{
    bool succ = false;

    do
    {
        try
        {
            using (Stream fileStream = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.None))
            {
                using (BinaryWriter bw = new BinaryWriter(fileStream))
                {
                    bw.Write(msg);

                    bw.Flush();
                    fileStream.Flush();
                    bw.Close();
                }
            }
            succ = true;
        }
        catch (IOException ex) { Console.WriteLine("Write Exception (addToBinary) : " + ex.Message); }
        catch (Exception ex) { Console.WriteLine("Some Exception occured (addToBinary) : " + ex.Message); return false; }
    } while (!succ);
    return true;
}

(bw.close也会关闭基础流)

在任何循环中使用它会导致输出,例如;

A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll
Write Exception (addToBinary) : The process cannot access the file 'C:\test\test.png' because it is being used by another process.

文件越大,弹出的错误就越多。它最终确实通过,但它显着降低了文件写入速度。它是导致异常的Stream fileStream =位。

我做错了什么?

使用示例;

do
{
    serverStream = clientSocket.GetStream();
    bytesRead = serverStream.Read(inStream, 0, buffSize); //How many bytes did we just read from the stream?

    recstrbytes = new byte[bytesRead]; //Final byte array
    Array.Copy(inStream, recstrbytes, bytesRead); //Copy from inStream to the final byte array
    addToBinary(recstrbytes, @"C:\test\test.png"); //Append final byte array to binary
    received += recstrbytes.Length; //Increment bytes received
}while (received < filesize);

2 个答案:

答案 0 :(得分:1)

在使用Stream读取文件之前,您需要先检查是否可以访问该文件。

您可以查看此链接:

Best way to handle errors when opening file

看看答案 虽然我发布了我的答案

https://stackoverflow.com/a/9503939/448407但您可以查看标记为答案的帖子。

如果您可以访问该文件,则只读取文件内容,我认为它将起作用。

答案 1 :(得分:1)

对于使用语句堆叠的人来说,一些好的建议风格明智。当您开始使用多个时,通常需要使用以下样式:

using (Stream fileStream = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.None))
using (BinaryWriter bw = new BinaryWriter(fileStream))
{
    bw.Write(msg);
    bw.Flush();
    fileStream.Flush();
    bw.Close();
}

我担心我无法解决你的问题,但我不确定如果第一次没有成功,反复尝试写入流是多么好的想法。