如何将二进制转换为字节并在c#中写为文件

Anu*_*uya 4 .net c#

我试图从数据库中读取二进制文件,并使用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);
    } 
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

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

byte[] fileAsByte = (byte[]) row["Blob"];
Run Code Online (Sandbox Code Playgroud)

如果失败,它至少应该表现出你是什么类型的实际DataRow.希望它是一种合理易于转换的类型byte[].