开发者

How to convert Binary to Byte and write as a file in c#

I am trying to read binary from开发者_运维技巧 database and write as a file in local disk using c#.

using the below code... But there is problem in this line : 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);
    } 
}


byte.Parse will try to parse a single byte. Have you tried just casting?

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

If that fails, it should at least show you what type is actually in the DataRow. Hopefully it's some type which is reasonably easily convertible to byte[].


If your column is of type varbinary(max), you can use GetSqlBytes or GetSqlBinary on the SqlDataReader. If your column is of type varchar(max) or nvarchar(max), use GetSqlChars on SqlDataReader. You can as well use, GetBytes {this takes a size of the array buffer} or GetSqlBytes.

Also, as suggested above, for varbinary(MAX) the following line as well should work

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

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜