C#中,将文件转换为字节可靠的方式[] [英] C#, reliable way to convert a file to a byte[]

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

问题描述

我在网上找到了下面的代码:

 专用字节[] StreamFile(字符串文件名)
{
的FileStream FS =新的FileStream(文件名,FileMode.Open,FileAccess.Read);

//创建文件流长度
字节一个字节数组[] =的ImageData新的字节[fs.Length]从字节流

//读取块入字节数组
fs.Read(的ImageData,0,System.Convert.ToInt32(fs.Length));

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

是否足够可靠的使用转换文件为byte []在C#中,还是有更好的方法来做到这一点?


解决方案

 字节[]字节= System.IO.File.ReadAllBytes(文件名); 

这是应该做的伎俩。 ReadAllBytes打开文件,读取内容到一个新的字节数组,然后将其关闭。下面是该方法的 MSDN页面


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.

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

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