110,534
社区成员
发帖
与我相关
我的任务
分享
FileStream fs = File.OpenRead(file);
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
而我觉得,一行足以var buffer = File.ReadAllBytes(file);
public static byte[] ReadFile(string file)
{
var result = new MemoryStream();
var fs = File.OpenRead(file);
var buffer = new byte[1024 * 8];
var len = 0;
while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
result.Write(buffer, 0, len);
return result.ToArray();
}
public static IEnumerable<byte[]> ReadFile(string file)
{
using (var fs = File.OpenRead(file))
{
var buffer = new byte[1024 * 20];
var len = 0;
while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
{
var result = new byte[len];
buffer.CopyTo(result, len);
yield return result;
}
}
}
这样使用迭代器机制来实现,就可以支持 IEnumerable 循环枚举。fs.Read(buffer, 0, buffer.Length);
这是错误的,这个方法返回了一个 int 整数,来说明 fs.Read 方法实际读取的字节数量,它完全有可能小于 buffer.Length。所以你看人家 InternalReadAllBytes 方法里边有一个 while 循环语句,这才是正确的编程。
所以你如果问你贴出的两个代码有什么本质区别,最本质地其实是,第一段是基础不好的程序员写出的有可能出 bug 的代码。第一段连正确定都不能保证,咱们就不管它是不是跟 InternalReadAllBytes 一样的功能了![System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static byte[] InternalReadAllBytes(String path, bool checkHost)
{
byte[] bytes;
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost)) {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB"));
int count = (int) fileLength;
bytes = new byte[count];
while(count > 0) {
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
index += n;
count -= n;
}
}
return bytes;
}
https://referencesource.microsoft.com/#mscorlib/system/io/file.cs,4b24188ee62795aa