C#把文件转成二进制数组

本文实现了在C#中,知道文件的路径后,读取该文件内容,并转换为byte数组返回的方法。

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class FileHelper{
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static byte[] ToBytes(string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open))
{
var buffer = new byte[1024];
using (var ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
}

调用示例:

1
2
3

var fileName="D://测试文件.txt";
var fileContent = FileHelper.ToBytes(fileName);

文本完

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×