c# - 检查上传文件的大小(以 mb 为单位)

标签 c#

我需要验证用户上传的文件不超过 10mb。这会完成工作吗?

var fileSize = imageFile.ContentLength;
if ((fileSize * 131072) > 10)
{
    // image is too large
}

我一直在看this thread , 和 this one ......但都没有让我一路走到那里。我正在使用 this作为转化率。

.ContentLength 获取以字节为单位的大小。然后我需要将它转换为 mb。

最佳答案

由于给定了以字节为单位的大小,因此您需要除以 1048576(即 1024 * 1024):

var fileSize = imageFile.ContentLength;
if ((fileSize / 1048576.0) > 10)
{
    // image is too large
}

但是如果预先计算 10mb 中的字节数,计算会更容易阅读:

private const int TenMegaBytes = 10 * 1024 * 1024;


var fileSize = imageFile.ContentLength;
if ((fileSize > TenMegaBytes)
{
    // image is too large
}

关于c# - 检查上传文件的大小(以 mb 为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43617227/

相关文章:

c# - 使用 LINQ,我如何选择特定索引处的项目?

C#计算int数组中值的平均值

c# - C# Windows 窗体中的状态栏

c# - 在 Entity Framework 拦截器中向 DbScanExpression 添加内部连接

c# - 没有堆栈跟踪的异常 - 怎么样?

c# - Microsoft Graph API 不返回我需要的属性

c# - 将 MemberExpression 应用于对象以检索属性值

c# - 将 List<XElement> 转换为 DataTable

c# - 时间旅行调试 : How to do it in C#?

c# - asp.net core razor pages 支持删除和放置请求