加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C#中将字节写入文件

发布时间:2020-12-16 01:41:07 所属栏目:百科 来源:网络整理
导读:我有一个来自Oracle数据库的BLOB.在.NET中,它是OracleLob类型,其中包括Read和ReadByte方法. int OracleLob.Read(byte[] buffer,int offset,int count)int OracleLob.ReadByte() 因此,Read方法读取一个字节序列,ReadByte一次读取一个字节.这是我的代码: Orac
我有一个来自Oracle数据库的BLOB.在.NET中,它是OracleLob类型,其中包括Read和ReadByte方法.

int OracleLob.Read(byte[] buffer,int offset,int count)
int OracleLob.ReadByte()

因此,Read方法读取一个字节序列,ReadByte一次读取一个字节.这是我的代码:

OracleLob ol = (OracleLob) cmd.Parameters[1].Value; //her er filen!!

BinaryWriter binWriter = new BinaryWriter(File.Open(@"D:wordfile.DOCX",FileMode.Create));
int currentByte = ol.ReadByte();

while (currentByte != -1)
{
   binWriter.Write(currentByte);
   currentByte = ol.ReadByte();
}

binWriter.Close();

但是当我在Word中打开wordfile.DOCX时,它表示该文件已损坏且无法打开.我究竟做错了什么?

解决方法

代码有什么问题,它在将字节数据写入BinaryWriter时使用了int值.它使用的是写入int而不是写入字节的重载,因此源中的每个字节都将写为4个字节.如果你检查文件大小,你会发现它的大小应该是它应该的四倍.

将值转换为byte,以便使用Write方法的正确重载:

binWriter.Write((byte)currentByte);

为了更有效地执行此操作,您可以使用缓冲区一次读取字节块而不是单个字节:

using (FileStream stream = File.Open(@"D:wordfile.DOCX",FileMode.Create)) {
  byte[] buffer = new byte[4096];
  int len = ol.Read(buffer,buffer.Length);
  while (len > 0) {
    stream.Write(buffer,len);
    len = ol.Read(buffer,buffer.Length);
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读