【问题标题】:Want to read file retrieved from database in the same format it was being saved in C# windowsForm想要以与保存在 C# windowsForm 中的相同格式读取从数据库中检索到的文件
【发布时间】:2013-05-15 00:33:51
【问题描述】:

我正在使用 C# Windows Form 应用程序将文档文件(word、pdf 和文本)插入到 SQL Server 数据库中,我使用以下代码将文件转换为二进制文件,然后将此文件上传到数据库:

    FileInfo fileinfo = new FileInfo(file);
    string fileName = System.IO.Path.GetFileNameWithoutExtension(file);
    string extension = System.IO.Path.GetExtension(file);
    long byteSize = fileinfo.Length;
    FileStream myFileStreams = new FileStream(file, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(myFileStreams);
    byte[] fileStream = br.ReadBytes((int)byteSize);

该文件已成功保存,但是当我从数据库中检索它时,该文件不是可读格式,我用于从数据库中检索并将其保存在本地磁盘上的以下代码:

    //the file is fetch by its id and is saved in DataTable dt1 on its row[0][1]
    byte[] cv = (byte[])dt1.Rows[0][1];
    string cvName = dt1.Rows[0][0].ToString();
    string ext = dt1.Rows[0][2].ToString();

    //saved in bin
    string pathOfCv = "new\\" + cvName + ext;
    File.WriteAllBytes(pathOfCv, cv);
    File.Create(pathOfCv);

检索到的文件有不可读的文本,我想以我保存的相同格式读取它,我认为文件转换存在问题可能是我无法直接在文件中写入字节数组。

请给我一些代码示例,我该如何解决这个问题,谢谢。

【问题讨论】:

  • DB 中的列类型是什么?这是二进制数据,应该像一个一样保存... MSSQL 有binary 列类型
  • 数据库中的列类型为varbinary(2000)
  • 您检查文件大小不 > 2000 吗?
  • 您遇到的一个问题是File.WriteAllBytes(pathOfCv, cv); 在给定路径创建了一个新文件,因此您的下一行File.Create(pathOfCv); 弊大于利。
  • 是的,文件太小了,现在不超过 10Kb,因为我现在正在测试

标签: c# sql-server-2005


【解决方案1】:

也许您应该尝试使用 MemoryStream 比如:

MemoryStream ms = new MemoryStream(cv);
FileStream file = new FileStream(cvName + ext, FileMode.Create,System.IO.FileAccess.Write);
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);
file.Close();
ms.Close();

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 2012-05-03
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多