將文件保存到數據庫中

//保存文件到SQL Server數據庫中
    private void FileToSql(string fileName,string tableName,string fieldName)
    {
        SqlConnection cn
=new SqlConnection ();
        FileInfo fi
=new FileInfo(fileName);
        FileStream fs
=fi.OpenRead();
        
byte[] bytes=new byte[fs.Length];
        fs.Read(bytes,
0,Convert.ToInt32(fs.Length));
        SqlCommand cm
=new SqlCommand();
        cm.Connection
=cn;
        cm.CommandType
=CommandType.Text;
        
if(cn.State==0) cn.Open();
        cm.CommandText
="insert into "+tableName+"("+fieldName+") values(@file)";
        SqlParameter spFile
=new SqlParameter("@file",SqlDbType.Image);
        spFile.Value
=bytes;
        cm.Parameters.Add(spFile);
        cm.ExecuteNonQuery();
    }
//保存文件到Access數據庫中
    private void FileToAccess(string fileName,string tableName,string fieldName)
    {
        OleDbConnection cn
=new OleDbConnection ();
        FileInfo fi
=new FileInfo(fileName);
        FileStream fs
=fi.OpenRead();
        
byte[] bytes=new byte[fs.Length];
        fs.Read(bytes,
0,Convert.ToInt32(fs.Length));
        OleDbCommand cm
=new OleDbCommand();
        cm.Connection
=cn;
        cm.CommandType
=CommandType.Text;
        
if(cn.State==0) cn.Open();
        cm.CommandText
="insert into "+tableName+"("+fieldName+") values(@file)";
        OleDbParameter spFile
=new OleDbParameter("@file",OleDbType.Binary);
        spFile.Value
=bytes;
        cm.Parameters.Add(spFile);
        cm.ExecuteNonQuery();
    }
    
//保存客戶端文件到數據庫,fl_name爲上傳控件
    private void FileToDataSourse(string mailid)
    {
        
string ConnStr = "";
        
string sql = "update t_mail set attachfilename=@attachfilename,attachfile=@attachfile where mailid=" + mailid;
        SqlCommand myCommand 
= new SqlCommand(sql, new SqlConnection(ConnStr));
        
string path = fl_name.PostedFile.FileName;
        
string filename = path.Substring(path.LastIndexOf(""+ 1, path.Length - path.LastIndexOf(""- 1);
        myCommand.Parameters.Add(
"@attachfilename", SqlDbType.VarChar);
        myCommand.Parameters[
"@attachfilename"].Value = filename;
        myCommand.Parameters.Add(
"@attachfile", SqlDbType.Image);
        Stream fileStream 
= fl_name.PostedFile.InputStream;
        
int intFileSize = fl_name.PostedFile.ContentLength;
        
byte[] fileContent = new byte[intFileSize];
        
int intStatus = fileStream.Read(fileContent, 0, intFileSize); //文件讀取到fileContent數組中
        myCommand.Parameters["@attachfile"].Value = ((byte[])fileContent);
        fileStream.Close();
        myCommand.Connection.Open();
        myCommand.ExecuteNonQuery();
        myCommand.Connection.Close();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章