编写并读取多个字节数组到文件中可以通过以下步骤实现:
byte[] byteArray1 = Encoding.ASCII.GetBytes("Hello");
byte[] byteArray2 = Encoding.ASCII.GetBytes("World");
FileStream
类来实现。例如:string filePath = "path_to_file"; // 替换为实际文件路径
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
// 在这里写入字节数组到文件
}
Write
方法将字节数组写入文件。例如:fileStream.Write(byteArray1, 0, byteArray1.Length);
fileStream.Write(byteArray2, 0, byteArray2.Length);
fileStream.Close();
byte[] readByteArray = new byte[byteArray1.Length + byteArray2.Length];
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
// 在这里从文件读取字节数组
fileStream.Read(readByteArray, 0, readByteArray.Length);
}
readByteArray
变量中包含了从文件中读取的字节数组。完整的示例代码如下所示:
using System;
using System.IO;
using System.Text;
namespace FileReadWriteExample
{
class Program
{
static void Main(string[] args)
{
byte[] byteArray1 = Encoding.ASCII.GetBytes("Hello");
byte[] byteArray2 = Encoding.ASCII.GetBytes("World");
string filePath = "path_to_file"; // 替换为实际文件路径
// 写入字节数组到文件
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
fileStream.Write(byteArray1, 0, byteArray1.Length);
fileStream.Write(byteArray2, 0, byteArray2.Length);
}
// 从文件读取字节数组
byte[] readByteArray = new byte[byteArray1.Length + byteArray2.Length];
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
fileStream.Read(readByteArray, 0, readByteArray.Length);
}
// 将读取的字节数组转换为字符串并输出
string result = Encoding.ASCII.GetString(readByteArray);
Console.WriteLine(result);
}
}
}
在上述示例中,请将 path_to_file
替换为实际的文件路径。