gpt4 book ai didi

c# - C# 中二进制文件的读写

转载 作者:行者123 更新时间:2023-12-03 08:44:56 24 4
gpt4 key购买 nike

我已经按照以下代码使用 C# 读取了一个二进制文件。然后我尝试将这个二进制数据写入另一个二进制文件中。但是我发现当我在Winmerge中打开这2个文件时,两个二进制文件是有区别的。即读取文件和写入文件。您能否建议一下,如果我只是读取文件并重写,为什么会有差异?

       string fileNameWithPath_ = "1.pwpmi";
string newfileNameWithPath_ = "2.pwpmi";

System.IO.FileStream fileStream = new System.IO.FileStream(fileNameWithPath_, System.IO.FileMode.Open,
System.IO.FileAccess.Read);
System.IO.BinaryReader binReader = new System.IO.BinaryReader(fileStream, Encoding.ASCII);


char[] chararr = new char[fileStream.Length];

chararr = binReader.ReadChars((int)fileStream.Length);
byte[] buffer = binReader.ReadBytes((int)fileStream.Length);

byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes,0, (int)fileStream.Length);

byte[] fileBytes = System.IO.File.ReadAllBytes(fileNameWithPath_);
string stringbyte1 = Encoding.ASCII.GetString(fileBytes);

binReader.Close();
fileStream.Close();
System.IO.BinaryWriter binWriter =
new System.IO.BinaryWriter(System.IO.File.Open(newfileNameWithPath_, System.IO.FileMode.Create));
binWriter.Flush();
binWriter.Write(stringbyte1);
binWriter.Close();

最佳答案

看来您已经尝试了几种不同的方法,并且实际上已经非常接近可行的方法。问题可能在于您将二进制数据作为一种数据类型读取并将其作为另一种数据类型写回输出的方式。尝试坚持字节:

    string fileNameWithPath_ = "1.pwpmi";
string newfileNameWithPath_ = "2.pwpmi";

System.IO.FileStream fileStream = new System.IO.FileStream(fileNameWithPath_, System.IO.FileMode.Open,
System.IO.FileAccess.Read);
System.IO.BinaryReader binReader = new System.IO.BinaryReader(fileStream, Encoding.ASCII);
byte[] fileBytes = binReader.ReadBytes((int)fileStream.Length);
//byte[] fileBytes = System.IO.File.ReadAllBytes(fileNameWithPath_); // this also works

binReader.Close();
fileStream.Close();
System.IO.BinaryWriter binWriter =
new System.IO.BinaryWriter(System.IO.File.Open(newfileNameWithPath_, System.IO.FileMode.Create));
binWriter.Flush();
binWriter.Write(fileBytes); // just feed it the contents verbatim
binWriter.Close();

上面的代码不会对传入的字节流进行任何更改,并且当我通过 WinMerge 运行它时会生成相同的文件

正如评论所建议的,您最好完全复制文件:

    string fileNameWithPath_ = "1.pwpmi";
string newfileNameWithPath_ = "2.pwpmi";
File.Copy(fileNameWithPath_, newfileNameWithPath_, overwrite: true);

关于c# - C# 中二进制文件的读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61861994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com