我在网上找到了以下代码:
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
}
Run Code Online (Sandbox Code Playgroud)
它是否足够可靠,可以在c#中将文件转换为byte [],还是有更好的方法可以做到这一点?
Eri*_*bes 206
byte[] bytes = System.IO.File.ReadAllBytes(filename);
Run Code Online (Sandbox Code Playgroud)
这应该够了吧.ReadAllBytes打开文件,将其内容读入新的字节数组,然后关闭它.这是该方法的MSDN页面.
Bri*_*sen 27
byte[] bytes = File.ReadAllBytes(filename)
Run Code Online (Sandbox Code Playgroud)
要么 ...
var bytes = File.ReadAllBytes(filename)
Run Code Online (Sandbox Code Playgroud)
Viv*_*vek 12
不要重复每个人已经说过的内容,但请妥善保存以下备忘单以进行文件操作:
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);
所有这些答案都带有.ReadAllBytes()
。在这里对SO提出了另一个类似的问题(我不会说重复,因为他们正试图重构其代码): 在C#中将大文件读入字节数组的最佳方法是?
对其中一个帖子发表了评论.ReadAllBytes()
:
File.ReadAllBytes throws OutOfMemoryException with big files (tested with 630 MB file
and it failed) – juanjo.arana Mar 13 '13 at 1:31
Run Code Online (Sandbox Code Playgroud)
对我来说,更好的方法是这样的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;
}
Run Code Online (Sandbox Code Playgroud)
但这就是我...
当然,所有这些都假定您有足够的内存来处理byte[]
读入File.Exists
的文件,而在进行此操作之前,我没有进行检查以确保文件在此处,因此您可以在调用此代码之前这样做。
归档时间: |
|
查看次数: |
152188 次 |
最近记录: |