您好,欢迎访问一九零五行业门户网

使用 FileStream 类读取字节数组并将其写入文件的 C# 程序

c# 是一种强大的面向对象的编程语言,用于开发各种应用程序。在本文中,我们将讨论如何使用 filestream 类编写一个 c# 程序,将字节数组读取并写入到文件中。
第一步:创建一个字节数组该程序的第一步是创建一个我们想要写入文件的字节数组。这是一个例子 -
byte[] bytearray = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64 };
第 2 步:将字节数组写入文件下一步是使用filestream类将字节数组写入文件。我们需要创建filestream类的一个新实例,并将文件路径、filemode、fileaccess和fileshare作为参数传递给其构造函数。下面是一个示例 -
string filepath = c:\myfile.txt;using (filestream filestream = new filestream(filepath, filemode.create, fileaccess.write, fileshare.none)) { filestream.write(bytearray, 0, bytearray.length);}
步骤3:从文件中读取字节数组要从文件中读取字节数组,我们需要创建 filestream 类的新实例,并将文件路径、filemode、fileaccess 和 fileshare 作为参数传递给其构造函数。然后,我们创建一个字节数组,并使用 filestream 类的 read() 方法将文件的内容读取到字节数组中。这是一个例子 -
byte[] readbytearray = new byte[bytearray.length];using (filestream filestream = new filestream(filepath, filemode.open, fileaccess.read, fileshare.read)) { filestream.read(readbytearray, 0, readbytearray.length);}
第四步:比较字节数组最后,我们需要比较原始字节数组和从文件中读取的字节数组,确保它们相同。我们可以使用 enumerable 类的 sequenceequal() 方法来比较两个字节数组。这是一个例子 -
bool areequal = bytearray.sequenceequal(readbytearray);
示例这是完整的 c# 程序 -
using system;using system.io;using system.linq;namespace bytearraytofile { class program { static void main(string[] args) { byte[] bytearray = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64 }; string filepath = c:\myfile.txt; // write byte array to file using (filestream filestream = new filestream(filepath, filemode.create, fileaccess.write, fileshare.none)) { filestream.write(bytearray, 0, bytearray.length); } // read byte array from file byte[] readbytearray = new byte[bytearray.length]; using (filestream filestream = new filestream(filepath, filemode.open, fileaccess.read, fileshare.read)) { filestream.read(readbytearray, 0, readbytearray.length); } // compare the byte arrays bool areequal = bytearray.sequenceequal(readbytearray); console.writeline(are the byte arrays equal? + areequal); } }}
输出
are the byte arrays equal? true
结论在本文中,我们学习了如何使用filestream类编写c#程序来读取和写入字节数组到文件中。这个程序可以在各种场景中使用,比如读取和写入图像或音频文件。通过理解本文涵盖的概念,您可以开发出更高级的需要文件输入和输出的应用程序。希望本文对您的编程之旅有所帮助。愉快编码!
以上就是使用 filestream 类读取字节数组并将其写入文件的 c# 程序的详细内容。
其它类似信息

推荐信息