C# Modulus Counting

本文关键字:Counting Modulus | 更新日期: 2023-09-27 18:18:09

大家好,

我正在写一个应用程序,我正在下载一个超过30MB的文件。我正在跟踪当前已下载的字节数。

我的问题是:

我想确定当我越过1M, 2M, 3M等等

我的逻辑是:

int totalFileSave = 0;
...
...
int bytesRead = responseStream.Read(buffer, 0, 4096);
totalFileSave += bytesRead;
while (bytesRead > 0) {
    // How do I test when I hit 1M, 2M, 3M and so forth...
    bytesRead = responseStream.Read(buffer, 0, 4096);
    totalFileSave += bytesRead;
}

C# Modulus Counting

private const int MEGABYTE = 1024 * 1024;
if ((bytesRead % MEGABYTE) == 0)
{
    // Do something...
}

这样如何:

private const int megaByte = 1024 * 1024;
private int current = 0;
while (bytesRead > 0) 
{
    bytesRead = responseStream.Read(buffer, 0, 4096);
    totalFileSave += bytesRead;
    int total = bytesRead / megaByte;
    if (total > current)
    {
        current = total;
        // you went up 1 M and are now at or greater than 'current'M
    }
}