C# 将文件转换为字节的可靠方法[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1497997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reliable way to convert a file to a byte[]
提问by JL.
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?
在 c# 中用于将文件转换为 byte[] 是否足够可靠,或者是否有更好的方法来做到这一点?
采纳答案by Erik Forbes
回答by vehomzzz
looks good enough as a generic version. You can modify it to meet your needs, if they're specific enough.
作为通用版本看起来足够好。如果它们足够具体,您可以对其进行修改以满足您的需求。
also test for exceptions and error conditions, such as file doesn't exist or can't be read, etc.
还测试异常和错误条件,例如文件不存在或无法读取等。
you can also do the following to save some space:
您还可以执行以下操作以节省一些空间:
byte[] bytes = System.IO.File.ReadAllBytes(filename);
回答by Brian Rasmussen
byte[] bytes = File.ReadAllBytes(filename)
or ...
或者 ...
var bytes = File.ReadAllBytes(filename)
回答by Eamon Nerbonne
Others have noted that you can use the built-in File.ReadAllBytes
. The built-in method is fine, but it's worth noting that the code you post above is fragile for two reasons:
其他人已经注意到您可以使用内置的File.ReadAllBytes
. 内置方法很好,但值得注意的是,您上面发布的代码很脆弱,原因有两个:
Stream
isIDisposable
- you should place theFileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read)
initialization in a using clause to ensure the file is closed. Failure to do this may mean that the stream remains open if a failure occurs, which will mean the file remains locked - and that can cause other problems later on.fs.Read
may read fewer bytes than you request. In general, the.Read
method of aStream
instance will read at least one byte, but not necessarily all bytes you ask for. You'll need to write a loop that retries reading until all bytes are read. This pageexplains this in more detail.
Stream
isIDisposable
- 您应该将FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read)
初始化放在 using 子句中以确保文件已关闭。不这样做可能意味着如果发生故障,流将保持打开状态,这将意味着文件保持锁定状态——这可能会在以后导致其他问题。fs.Read
读取的字节数可能少于您请求的字节数。通常,实例的.Read
方法Stream
将读取至少一个字节,但不一定读取您要求的所有字节。您需要编写一个循环来重试读取,直到读取完所有字节。 此页面更详细地解释了这一点。
回答by Vivek
Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:
不要重复每个人已经说过的内容,而是保留以下备忘单以方便文件操作:
System.IO.File.ReadAllBytes(filename);
File.Exists(filename)
Path.Combine(folderName, resOfThePath);
Path.GetFullPath(path); // converts a relative path to absolute one
Path.GetExtension(path);
System.IO.File.ReadAllBytes(filename);
File.Exists(filename)
Path.Combine(folderName, resOfThePath);
Path.GetFullPath(path); // converts a relative path to absolute one
Path.GetExtension(path);
回答by vapcguy
All these answers with .ReadAllBytes()
. Another, similar (I won't say duplicate, since they were trying to refactor their code) question was asked on SO here: Best way to read a large file into a byte array in C#?
所有这些答案都带有.ReadAllBytes()
. 另一个类似(我不会说重复,因为他们试图重构他们的代码)问题在这里被问到: Best way to read a large file into a byte array in C#?
A comment was made on one of the posts regarding .ReadAllBytes()
:
对其中一个帖子发表了评论.ReadAllBytes()
:
File.ReadAllBytes throws OutOfMemoryException with big files (tested with 630 MB file
and it failed) – juanjo.arana Mar 13 '13 at 1:31
A better approach, to me, would be something like this, with BinaryReader
:
对我来说,更好的方法是这样的BinaryReader
:
public static byte[] FileToByteArray(string fileName)
{
byte[] fileData = null;
using (FileStream fs = File.OpenRead(fileName))
{
var binaryReader = new BinaryReader(fs);
fileData = binaryReader.ReadBytes((int)fs.Length);
}
return fileData;
}
But that's just me...
但这只是我...
Of course, this all assumes you have the memory to handle the byte[]
once it is read in, and I didn't put in the File.Exists
check to ensure the file is there before proceeding, as you'd do that before calling this code.
当然,这一切都假设您有足够的内存来处理byte[]
读入后的内容,并且File.Exists
在继续之前我没有进行检查以确保文件在那里,就像您在调用此代码之前所做的那样。