2011-11-01 33 views
4

我已經介紹了幾種將數據插入SQL Server的不同方法(適用於FileStream)。插入FileStream對象的最佳方法是什麼?下面的方法之間的主要區別是一個插入,另一個插入FileStream對象的佔位符。SQL Server FileStream如何填充文件流列

一種方法是,他們通過C#通過插入直接插入文檔:

鏈接:FileStream

con.Open(); 
    string sql = "INSERT INTO MyFsTable VALUES (@fData, @fName, default)"; 
    SqlCommand cmd = new SqlCommand(sql, con); 
    cmd.Parameters.Add("@fData", SqlDbType.Image, fileData.Length).Value = fileData; 
    cmd.Parameters.Add("@fName", SqlDbType.NVarChar).Value = fi.Name; 
    cmd.ExecuteNonQuery(); 
    con.Close(); 

它們插入一排,但留下的文件的另一種方法(的FileStream列)null。我不得不把在一個虛擬的值,因爲當FILESTREAM字段爲空我獲取文件路徑調用返回NULL:

鏈接:FileStream

5: if (FileUpload1.FileContent.Length > 0) 
    6: { 
    7:  SqlConnection objSqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); 
    8:  objSqlCon.Open(); 
    9:  SqlTransaction objSqlTran = objSqlCon.BeginTransaction(); 
    10: 
    11:  SqlCommand objSqlCmd = new SqlCommand("FileAdd",objSqlCon,objSqlTran); 
    12:  objSqlCmd.CommandType = CommandType.StoredProcedure; 
    13: 
    14:  SqlParameter objSqlParam1 = new SqlParameter("@SystemNumber", SqlDbType.Int); 
    15:  objSqlParam1.Value = "1"; 
    16: 
    17:  SqlParameter objSqlParam2 = new SqlParameter("@FileType", SqlDbType.VarChar,4); 
    18:  objSqlParam2.Value = System.IO.Path.GetExtension(FileUpload1.FileName); 
    19: 
    20:  SqlParameter objSqlParamOutput = new SqlParameter("@filepath", SqlDbType.VarChar, -1); 
    21:  objSqlParamOutput.Direction = ParameterDirection.Output; 
    22: 
    23:  objSqlCmd.Parameters.Add(objSqlParam2); 
    24:  objSqlCmd.Parameters.Add(objSqlParam1); 
    25:  objSqlCmd.Parameters.Add(objSqlParamOutput); 
    26: 
    27: 
    28:  objSqlCmd.ExecuteNonQuery(); 
    29: 
    30:  string Path = objSqlCmd.Parameters["@filepath"].Value.ToString(); 
    31: 
    32:  objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran); 
    33: 
    34:  byte[] objContext = (byte[])objSqlCmd.ExecuteScalar(); 
    35:  
    36: 
    37:  SqlFileStream objSqlFileStream = new SqlFileStream(Path, objContext, FileAccess.Write); 
    38:  
    39:  objSqlFileStream.Write(buffer, 0, buffer.Length); 
    40:  objSqlFileStream.Close(); 
    41: 
    42:  objSqlTran.Commit(); 

回答

6

FILESTREAM MVC: Download and Upload images from SQL Server爲例說明如何上傳和下載文件流以高效,面向流的方式。你所追求的方法是將緩衝區分配爲整個上傳文件的大小(並且我假設你也是在服務內容時也是這樣做的)效率非常低,你的ASP進程內存將被這麼大的字節[]操作。

+0

謝謝@Remus我很感激。 – scarpacci