c# - 防病毒软件显着减慢了磁盘写入速度,是否有解决方法可以防止将数据存储在内存中?

标签 c#

假设我通过套接字流接收一个文件,一次接收 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 似乎直到完成才接受它,而且它几乎不会增加进程的内存使用量。这里有什么大 secret ?

附加到我正在使用的二进制函数(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;
}

最佳答案

我看到你每次写入数据时都会重新打开文件。为什么不保持文件流打开?每次关闭它时,防病毒软件都会对其进行扫描,因为它已被修改。

还有一个建议,WriteLine 函数的工作方式类似于 C++ 中的 printf,所以...而不是这样做:

Console.WriteLine("Appending "+msg.Length+" bytes of data.");

你可以这样做:

Console.WriteLine("Appending {0} bytes of data.", msg.Length);

这有时确实可以节省您的时间。

关于c# - 防病毒软件显着减慢了磁盘写入速度,是否有解决方法可以防止将数据存储在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11248686/

相关文章:

c# - 如何正确比较列表

c# - 无法将类型 'System.ConsoleKey'隐式转换为 'char'

c# - UWP 应用程序无法启动

c# - Entity Framework 6 导航集合为空而不是空

c# - 对父列表中的每个子列表执行 'OrderByDescending'

c# - 如何创建一个方法来创建一个新的列表并接受额外的参数

c# - WPF Grid.IsSharedSizeScope 跨多个网格

c# - .NET:如何判断编码是否支持我的字符串中的所有字符?

c# - 多态性:派生自基类中的 protected 成员?

c# - 以阿拉伯语格式显示日期 'Wednesday, May 22, 2013'