简体   繁体   English

FileStream获取错误算术运算导致溢出

[英]FileStream get error Arithmetic operation resulted in an overflow

I try to get bytes from file using this method 我尝试使用这种方法从文件中获取字节

byte[] b1;
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    b1= new byte[fs.Length];
                    int bytesRead = fs.Read(b1, 0, b1.Length);
                } 

but when i test it with file size = 4.9GB its throw exception say Arithmetic operation resulted in an overflow. 但是,当我使用文件大小= 4.9GB对其进行测试时,它的抛出异常表示算术运算导致溢出。

A byte[] can only have a maximum length of 2,147,483,647. byte[]的最大长度只能为2,147,483,647。 Trying to create a btye[] that is longer than that will cause an OverflowException to be thrown 试图创建一个比该更长的btye[]将导致抛出OverflowException

Basically, to check for arithmetic overflow exceptions in your solution you can set in your Project Properties -> Build -> Advanced -> Check for arithmetic overflow/underflow 基本上,要检查解决方案中的算术溢出异常,可以在项目属性->构建->高级->检查算术溢出/下溢中进行设置

But this property may cause performance issues at runtime. 但是此属性可能会在运行时导致性能问题。 Therefore, one must be careful in using integers. 因此,在使用整数时必须小心。 As pointed above, your file size is 4.9GB so 4,900,000,000 > 2,147,483,647 (which you can check using Int32.MaxValue in c#) 如上所述,您的文件大小为4.9GB,因此4,900,000,000> 2,147,483,647(您可以在c#中使用Int32.MaxValue进行检查)

To resume, when you're using filestream you must check your input parameters and expect these type of issues by adding some try catch blocks to avoid unhandled exceptions that result in a bad experience for the user. 要恢复,在使用文件流时,必须检查您的输入参数,并通过添加一些try catch块来避免出现未处理的异常(这些异常会给用户带来不好的体验),以期望出现此类问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM