如何转换为二进制字节和写在C#中的文件 [英] How to convert Binary to Byte and write as a file in c#
本文介绍了如何转换为二进制字节和写在C#中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想读取数据库二进制和使用C#写在本地磁盘上的文件。
使用下面的code ...
但是,问题在这一行:字节[] fileAsByte = byte.Parse(行[斑点]);
公共静态无效ReadBlob()
{
INT ICOUNT = 0;
字符串文件名;
SqlConnection的Mycon =新的SqlConnection(CON);
Mycon.Open();
字符串查询字符串=选择*+ TblName;
SqlDataAdapter的适配器=新的SqlDataAdapter(查询字符串,Mycon);
数据表dtBlob =新的DataTable();
adapter.Fill(dtBlob);
的foreach(DataRow的行dtBlob.Rows)
{
byte []的fileAsByte = byte.Parse(行[斑点]);
。文件名=文件路径+ TblName +行[BlobId]的ToString()+文件类型;
WriteBlob(fileAsByte,文件名);
}
Mycon.Close();
}
公共静态无效WriteBlob(byte []的BUFF,字符串文件名)
{
尝试
{
的FileStream FS =新的FileStream(文件名,FileMode.Create,FileAccess.ReadWrite);
的BinaryWriter体重=新的BinaryWriter(FS);
bw.Write(BUFF);
bw.Close();
}
赶上(例外前)
{
Console.WriteLine(ex.Message);
}
}
解决方案
byte.Parse
将尝试解析的单的字节。您是否尝试过铸造?
字节[] fileAsByte =(字节[])行[斑点];
如果失败的话,应该至少说明你是什么类型的实际上的在的DataRow
。希望它的一些类型,是相当容易地转换为字节[]
。
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[]
.
这篇关于如何转换为二进制字节和写在C#中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文