C#保存byte[]到数据库和读取,把byte[]写进⽂件⽂件中
只能⽤参数传值的⽅式才能把byte[]的内容保存到数据
数据库中的字段类型为: varbinary
/// <summary>
/// 保存模板
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static bool TemplateSave(TemplateEntity t)
{
bool boo = false;
try
{
if (BaseDataAccess.ExecuteQuery("SELECT * FROM TemplateEntity WHERE Name=N'" + t.Name + "'").Rows.Count > 0) throw new Exception("模板 [" + t.Name + "] 已存在");
SqlParameter[] par = { new SqlParameter("@Description",t.Description) ,
new SqlParameter("@TemplateFile",t.TemplateFile)//byte[]数组内容
};
string sql = @"
INSERT INTO dbo.TemplateEntity
( Id ,
Memo ,
CreateDate ,
LastEditDate ,
Printer ,
Name ,
[FileName] ,
[Description],
TemplateFile
)
VALUES ( NEWID(),
N'" + t.Memo + @"' ,
GETDATE() ,
GETDATE() ,
N'" + t.Printer + @"' ,
N'" + t.Name + @"' ,
N'" + t.FileName + @"' ,
@Description ,
@TemplateFile)";
if (BaseDataAccess.ExcuteNonQuery(sql, par) > 0)
boo = true;
}
catch (Exception ex)
{
throw ex;
}
return boo;
}
/// <summary>
/// 根据ID查询打印模板
/// </summary>
/// <param name="id"></param>
/
// <returns></returns>
public static TemplateEntity GetObjectsById(string id)
{
//return BaseNhibernate<TemplateEntity>.GetObjectsByFrom("from TemplateEntity o where o.Name='" + id + "'").FirstOrDefault(); TemplateEntity t = null;
try
{
DataTable dt = BaseDataAccess.ExecuteQuery("SELECT TOP 1 * FROM TemplateEntity WHERE Name=N'" + id + "'");
if (dt.Rows.Count > 0)
{
t = new TemplateEntity();
t.Id = new Guid(dt.Rows[0]["Id"].ToString());
t.FileName = dt.Rows[0]["FileName"].ToString();
t.Name = dt.Rows[0]["Name"].ToString();
t.Description = dt.Rows[0]["Description"].ToString();
t.Printer = dt.Rows[0]["Printer"].ToString();
if (string.IsNullOrEmpty(dt.Rows[0]["TemplateFile"].ToString()))
throw new Exception("请重新上传打印模板 [ " + t.Name + " ]");
t.TemplateFile = (byte[])dt.Rows[0]["TemplateFile"];
}
}
catch (Exception ex)
{
throw ex;
}
return t;
}
public static string TagsTemplateDir = AppDomain.CurrentDomain.BaseDirectory + @"TagsTemplate";
/// <summary>
/// 下载模板到本地⽂件夹中
/// </summary>
/// <param name="t"></param>
public static void GetTemplateFile(TemplateEntity t)
{
try
{
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
Stream postStream = myWebClient.OpenWrite(TagsTemplateDir + "\\" + t.FileName, "PUT");
postStream.Write(t.TemplateFile, 0, t.TemplateFile.Length);
postStream.Close();
}
catch (Exception ex)
param name
{
throw ex;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。