Anuya
Anuya

Reputation: 8350

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);
    } 
}

Upvotes: 4

Views: 4855

Answers (2)

Sanket Naik
Sanket Naik

Reputation: 215

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503290

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[].

Upvotes: 5

Related Questions