【发布时间】:2020-09-03 19:16:17
【问题描述】:
我已按照以下代码使用 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();
【问题讨论】:
-
这段代码中唯一可以保存的可能是
System.IO.FileStream fileStream = new System.IO.FileStream(...)。你能描述一下你真正想要做什么吗?您只是想创建文件的副本吗?还是更改第一个部分的某些部分,将结果保存在第二个中?还有什么? -
你为什么要让这件事变得比
File.Copy(srcPath, dstPath)更难,或者最坏的情况(如果你真的想拦截或转换你复制的数据):File.WriteAllBytes(dstPath, File.ReadAllBytes(srcPath))?
标签: c# binary binaryfiles binaryreader binarywriter