1

标题真的说明了一切。

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

2 回答 2

1

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

你可以看看这个链接:

打开文件时处理错误的最佳方法

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

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

仅当您可以访问文件时才读取文件内容,我认为它会起作用。

于 2012-06-28T15:52:14.440 回答
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();
}

恐怕我无法解决您的问题,但我不确定如果第一次不成功,反复尝试写入流是一个好主意。

于 2012-06-28T15:59:14.623 回答