将文件转换为字节的可靠方法 [英] Reliable way to convert a file to a byte[]

查看:75
本文介绍了将文件转换为字节的可靠方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了以下代码:

 私有字节[] StreamFile(string filename)
{
FileStream fs = new FileStream(文件名,FileMode.Open,FileAccess.Read);

//创建文件流长度的字节数组
byte [] ImageData = new byte [fs.Length];

//将字节流从流读取到字节数组
fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));

//关闭文件流
fs.Close();
返回ImageData; //返回字节数据
}

是否足够可靠,可以用来转换文件到c#中的byte [],还是有更好的方法呢?

解决方案

  byte [] bytes = System.IO.File.ReadAllBytes(filename); 

这应该可以解决问题。 ReadAllBytes将打开文件,将其内容读取到新的字节数组中,然后关闭它。这是该方法的 MSDN页面。 / p>

I found the following code on the web:

private byte [] StreamFile(string filename)
{
   FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);

   // Create a byte array of file stream length
   byte[] ImageData = new byte[fs.Length];

   //Read block of bytes from stream into the byte array
   fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));

   //Close the File Stream
   fs.Close();
   return ImageData; //return the byte data
}

Is it reliable enough to use to convert a file to byte[] in c#, or is there a better way to do this?

解决方案

byte[] bytes = System.IO.File.ReadAllBytes(filename);

That should do the trick. ReadAllBytes opens the file, reads its contents into a new byte array, then closes it. Here's the MSDN page for that method.

这篇关于将文件转换为字节的可靠方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆