【问题标题】:How to convert Binary to Byte and write as a file in c#如何将二进制转换为字节并在c#中写入文件
【发布时间】:2011-04-29 08:31:39
【问题描述】:

我正在尝试从数据库中读取二进制文件并使用 c# 在本地磁盘中写入文件。

使用下面的代码... 但是这一行有问题:byte[] fileAsByte = byte.Parse(row["Blob"]);

public static void ReadBlob()
{ 
    int icount = 0;
    string FileName;
    SqlConnection Mycon = new SqlConnection(Con);
    Mycon.Open();
    string queryString = "select * from " + TblName;
    SqlDataAdapter adapter = new SqlDataAdapter(queryString, Mycon);

    DataTable dtBlob = new DataTable();
    adapter.Fill(dtBlob);


    foreach (DataRow row in dtBlob.Rows)
    {
        byte[] fileAsByte = byte.Parse(row["Blob"]);
        FileName = FilePath + TblName + row["BlobId"].ToString() + FileType;

        WriteBlob(fileAsByte, FileName);
    }

    Mycon.Close();
}

public static void WriteBlob(byte[] buff, string fileName)
{
    try
    {
        FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(buff);
        bw.Close(); 
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    } 
}

【问题讨论】:

  • 发生了什么?乍一看,唯一的问题是文件名,它将具有行值:“ row["BlobId"].ToString() "。
  • 究竟什么是“问题”?我大概可以猜到……但是你得到一个例外吗?如果是这样,请发布整个异常消息。您向我们提供的信息越多,您获得的实际帮助就越多。

标签: c# .net


【解决方案1】:

byte.Parse 将尝试解析 单个 字节。你试过只投射吗?

byte[] fileAsByte = (byte[]) row["Blob"];

如果失败,它至少应该在DataRow 中显示实际上 是什么类型。希望它是某种可以相当容易地转换为byte[] 的类型。

【讨论】:

  • 我会做一个“类型安全转换”:byte[] fileAsByte = (row["Blob"]) as byte;(至少在 .NET 3.5,VS2008 中)
  • @corlettk:我不会。如果转换失败,我会想要它抛出一个异常,假设这是应该始终存在的必需数据。仅当转换失败有效时使用as
  • @corlettk:如果您认为(byte[])data 不安全但data as byte[] 是安全的,那您就错了。无论您使用什么语法,.NET 都是类型安全的。唯一的区别是,如果data 不是byte[] 类型,第一个将引发异常,但第二个将返回null 引用。
  • /Hemant:谢谢你们俩的澄清......谦虚的馅饼......遗憾的笑容。
【解决方案2】:

如果您的列是 varbinary(max) 类型,您可以在 SqlDataReader 上使用 GetSqlBytes 或 GetSqlBinary。如果您的列是 varchar(max) 或 nvarchar(max) 类型,请在 SqlDataReader 上使用 GetSqlChars。您也可以使用 GetBytes {这需要数组缓冲区的大小} 或 GetSqlBytes。

此外,如上所述,对于 varbinary(MAX),以下行也应该有效

byte[] binaryData = (byte[])row["Blob"];

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-06-06
    • 2010-12-08
    • 2022-12-09
    • 2011-01-25
    • 1970-01-01
    • 2011-11-28
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多