C# c语言中二进制文件的读写
我已经按照下面的代码用C读了一个二进制文件。然后我试着把这个二进制数据写到另一个二进制文件中。但我发现,当我在Winmerge中打开这两个文件时,两个二进制文件都存在差异。i、 e读文件和写文件。 你能不能告诉我,如果我只是阅读文件并重写,为什么会有不同C# c语言中二进制文件的读写,c#,binary,binaryfiles,binaryreader,binarywriter,C#,Binary,Binaryfiles,Binaryreader,Binarywriter,我已经按照下面的代码用C读了一个二进制文件。然后我试着把这个二进制数据写到另一个二进制文件中。但我发现,当我在Winmerge中打开这两个文件时,两个二进制文件都存在差异。i、 e读文件和写文件。 你能不能告诉我,如果我只是阅读文件并重写,为什么会有不同 string fileNameWithPath_ = "1.pwpmi"; string newfileNameWithPath_ = "2.pwpmi"; System.IO.FileStream
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();
看起来你已经尝试了一些不同的方法,实际上已经非常接近于有效的方法。问题可能在于您将二进制数据作为一种数据类型读取,并将其作为另一种数据类型写入输出的方式。尝试粘贴到字节: 字符串filename,路径为1.pwpmi; 字符串newfilename,路径为2.pwpmi; System.IO.FileStream FileStream=新的System.IO.FileStream文件名和路径,System.IO.FileMode.Open, System.IO.FileAccess.Read; System.IO.BinaryReader binReader=新System.IO.BinaryReaderfileStream,Encoding.ASCII; byte[]fileBytes=binReader.ReadBytesintfileStream.Length; //byte[]fileBytes=System.IO.File.ReadAllBytesfileNameWithPath;//这同样有效 binReader.Close; fileStream.Close; System.IO.BinaryWriter binWriter= 新建System.IO.BinaryWriterSystem.IO.File.OpennewfileNameWithPath_,System.IO.FileMode.Create; binWriter.Flush; binWriter.WritefileBytes;//只需逐字输入内容即可 binWriter.Close; 上面的代码不会对传入的字节流进行任何更改,当我通过WinMerge运行它时,会生成相同的文件 正如评论所建议的那样,您最好完全复制该文件: 字符串filename,路径为1.pwpmi; 字符串newfilename,路径为2.pwpmi; File.CopyfileNameWithPath_u,newfileNameWithPath_u,overwrite:true;
.NET framework提供了一种用于复制文件的内置方法:
File.Copy(fileNameWithPath_, newfileNameWithPath_)
这里的文件是System.IO.File
或者:
using (FileStream inStream = new FileStream(fileNameWithPath_, FileMode.Open, FileAccess.Read))
using (FileStream outStream = new FileStream(newfileNameWithPath_, FileMode.Create, FileAccess.Write))
{
inStream.CopyTo(outStream);
}
此代码中唯一可以保存的部分可能是System.IO.FileStream FileStream=new System.IO.FileStream。。。。你能描述一下你到底想做什么吗?您只是想创建文件的副本吗?或者更改第一部分的某些部分,将结果保存在第二部分?还有什么?你为什么要比File.copyrcpath、dstPath更难呢?如果你真的想截获或转换你复制的数据,最坏的情况是:File.writealBytessPath、File.ReadAllBytessrcPath?我不想复制文件,我想在另一个文件中写入二进制数据。你的代码运行得很好。谢谢