[英]Export blob from remote sql server and save to file on disk where sql server is located [C#]
[英]sqlfilestream - getting blob data from SQL Server and saving the file locally to disk
我有以下情況:
我已成功使用FILESTREAM將文件(各種擴展名)保存到我的sql server數據庫中。 這些內容可以是圖片,也可以是文字doc,pdf等。
現在我想檢索它們並將它們另存為文件到我的本地目錄中。
這是我到目前為止所擁有的
我的函數調用SQL並獲取我想要的文件流信息
public static void SelectFile(string sourceId)
{
string serverPath;
string filename;
byte[] serverTxn;
using (TransactionScope ts = new TransactionScope())
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConn"].ToString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("OPS.LoadFileBlobFromSQL", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@AttachmentId", SqlDbType.VarChar).Value = sourceId;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
filename = rdr.GetSqlString(0).Value;
serverPath = rdr.GetSqlString(1).Value;
serverTxn = rdr.GetSqlBinary(2).Value;
rdr.Close();
}
}
StreamObjectFromFilestream(serverPath, serverTxn, filename);
}
ts.Complete();
}
}
private static void StreamObjectFromFilestream(string serverPath, byte[] serverTxn, string filename)
{
SqlFileStream sfs = new SqlFileStream(serverPath, serverTxn, FileAccess.Read);
byte[] buffer = new byte[sfs.Length];
sfs.Read(buffer, 0, buffer.Length);
System.IO.File.WriteAllBytes(@"c:\test\hello.pdf", buffer);
sfs.Close();
}
我正在獲取serverpath,文件名和serverTxn ..但是當我進入StreamObjectFromFilestream函數時,緩沖區為空..我知道我在這里缺少一些簡單的東西...只是不知道什么。
朝正確方向的任何指針將不勝感激。
謝謝,科里
您可以跳過使用StreamObjectFromFilestram中的SqlFilestream,您的serverTxn已經是方法WriteAllBytes需要的字節數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.