假设我正在通过套接字流接收文件,我一次接收 1024 个字节。每次我写入硬盘时,我的防病毒软件都会扫描整个文件。文件越大,写入下一个 1024 字节所需的时间就越长。更不用说“文件正在被另一个进程使用”错误。
我目前的解决方法是将字节存储在内存中的字节数组中,最多 X 兆字节(用户定义),每次填满时,字节数组都会附加到硬盘上的文件中。
byte[] filebytearray = new byte[filesize]; //Store entire file in this byte array.
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 this loop
Array.Copy(inStream, recstrbytes, bytesRead); //Copy from inStream to the final byte array this loop
Array.Copy(recstrbytes, 0, filebytearray, received, bytesRead); //Copy the data from the final byte array this loop to filebytearray
received += recstrbytes.Length; //Increment bytes received
}while (received < filesize);
addToBinary(filebytearray, @"C:\test\test.exe"); //Append filebytearray to binary
(在这个简化的示例中,它只是将整个文件存储在内存中,然后再将其卸载到硬盘中)
但我绝对讨厌这种方法,因为它显着增加了我的程序使用的内存。
其他程序员如何解决这个问题?例如,当我使用 Firefox 下载时,它只是以全速下载,我的 AV 似乎在完成之前不会将其拾取,并且它几乎不会增加进程的内存使用量。这里有什么大秘密?
附加到我正在使用的二进制函数(WIP):
private bool addToBinary(byte[] msg, string filepath)
{
Console.WriteLine("Appending "+msg.Length+" bytes of data.");
bool succ = false;
do
{
try
{
using (Stream fileStream = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.None))
{
fileStream.Write(msg, 0, msg.Length);
fileStream.Flush();
fileStream.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;
}