我已经按照以下代码使用C#读取了一个二进制文件。然后,我尝试将此二进制数据写入另一个二进制文件。但是我发现,当我在Winmerge中打开这两个文件时,两个二进制文件都存在差异。即读取文件和写入文件。请问如果我只是读取文件并重写,为什么会有区别?
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();
似乎您尝试了几种不同的方法,但实际上已经接近可行的方法。问题可能是您以一种数据类型读取二进制数据,然后以另一种类型将其写回到输出中。尝试坚持[C0]:
bytes
上面的代码没有对传入的字节流进行任何更改,并且当我通过WinMerge运行它时会产生相同的文件
正如评论所建议,最好完全复制文件:
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();
。NET框架提供了一种复制文件的内置方法:
string fileNameWithPath_ = "1.pwpmi";
string newfileNameWithPath_ = "2.pwpmi";
File.Copy(fileNameWithPath_, newfileNameWithPath_, overwrite: true);
((这里File.Copy(fileNameWithPath_, newfileNameWithPath_)
是File
。]
或替代:
System.IO.File