using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
namespace BLL
{
public class ClsFile
{
private string _server = string.Empty;
private string _database = string.Empty;
private string _uid = string.Empty;
private string _pwd = string.Empty;
private string _sqlConnection = string.Empty;
public ClsFile(string server, string database, string uid, string pwd)
{
_server = server;
_database = database;
_uid = uid;
_pwd = pwd;
_sqlConnection = "server=" + _server + ";database=" + _database + ";uid=" + _uid + ";pwd=" + _pwd;
}
//插入图片(table 表名、fieldName 存储文件字段名、sPath 文件完整路径)【程序上传使用,存入HX_UPDATE】
///
///
///
/// 表名
/// 存储文件字段名
/// 文件名
/// 版本号
/// 文件大小
/// 文件完整路径
///
///
public bool Insert_File(string table, string fieldName, string sName, long sNo, long sSize, string sPath, ref string sErr)
{
try
{
SqlConnection con = new SqlConnection(_sqlConnection);
con.Open();
byte[] FileList = this.FileToByteArray(sPath);
string commandText = @" INSERT INTO " + table + "(" + fieldName + ") " +
"VALUES ('" + sName + "'," + sNo.ToString() + ",@FileList," + sSize.ToString() + ")";
SqlCommand comm = new SqlCommand(commandText, con);
comm.Parameters.AddWithValue("@FileList", FileList);
comm.ExecuteNonQuery();
con.Close();
}
catch (Exception e)
{
sErr = e.Message;
return false;
}
return true;
}
//插入图片(table 表名、fieldName 存储文件字段名、sPath 文件完整路径)
public bool Insert_File(string table, string fieldName,long HInterID,int HEntryID,string sPath, ref string sErr)
{
try
{
SqlConnection con = new SqlConnection(_sqlConnection);
con.Open();
byte[] FileList = this.FileToByteArray(sPath);
string commandText = @" INSERT INTO " + table + "(" + fieldName + ") " +
"VALUES (" + HInterID.ToString() + "," + HEntryID.ToString() + ",@FileList,'" + sPath + "')";
SqlCommand comm = new SqlCommand(commandText, con);
comm.Parameters.AddWithValue("@FileList", FileList);
comm.ExecuteNonQuery();
con.Close();
}
catch(Exception e)
{
sErr = e.Message;
return false;
}
return true;
}
//把文件转换成byte[]
public byte[] FileToByteArray(String FilePath)
{
FileStream stream = new FileInfo(FilePath).OpenRead();
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
return buffer;
}
//读取 fieldName 该字段中符合条件的所有文件(sql SQL查询语句、fieldName 存储图片字段名)
public void Get_File(string sql, string fieldName,string FileName)
{
List InformatoinCollection = new List();
SqlConnection cn = new SqlConnection(_sqlConnection);
cn.Open();
SqlCommand cm = new SqlCommand(sql, cn);
SqlDataReader dr = cm.ExecuteReader();
byte[] oFile = null;
if (dr.Read())
{
oFile = (byte[])dr[fieldName];
}
FileStream fs;
FileInfo fi = new FileInfo(FileName);
fs = fi.OpenWrite();
fs.Write(oFile, 0, oFile.Length);
fs.Close();
dr.Close();
cn.Close();
}
}
}