标题真的说明了一切。
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);