[轉貼] 非同步(Async)讀取、寫入BLOB檔案

https://www.dotblogs.com.tw/mis2000lab/2016/01/11/async_file_blob

今天在MSDN上找到好範例,

可以搭配檔案上傳(FileUpload),用 .NET 4.5起的「非同步(Async)」方法,做檔案讀取與寫入


MSDN範例來源: https://msdn.microsoft.com/zh-tw/library/hh556234(...

上述網頁的下方,分別提供「讀取」與「寫入」兩種範例。

除了二進位檔案(BLOB)之外,也提供大型文字檔、大型XML檔的讀寫範例,值得學習。


這個範例可以搭配書本上集(ASP.NET專題實務(I)  /  松崗出版)

第十八章 FileUpload檔案上傳

如果我們把BLOB二進位檔案寫入資料庫,可以研習這個範例

用 .NET 4.5起的「非同步 (Async)」的方法來讀取、寫入,增加效率。


搭配的資料表

名為Streams的資料表,裡面有三個資料流的欄位:
    欄位textdata,資料型態為NVarChar(MAX)。
    欄位bindata,資料型態為VarBinary(MAX)。以前的SQL Server可用Image來代替。
    欄位xmldata,資料型態為XML。
 

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Threading.Tasks;

完整範例請參閱微軟MSDN網站。


      // Application retrieving a large BLOB from SQL Server in .NET 4.5 using the new asynchronous capability
      private static async Task CopyBinaryValueToFile() 
      {
         string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "二進位檔案的檔名");
         // 檔案位置(路徑與檔名),我的文件底下的二進位檔案

         using (SqlConnection conn = new SqlConnection("DB連結字串")) {
            await conn.OpenAsync();
            
            using (SqlCommand cmd = new SqlCmd("SELECT [bindata] FROM [資料表] WHERE [id]=123", conn)) 
            {  // The reader needs to be executed with the SequentialAccess behavior to enable network streaming
               // Otherwise ReadAsync will buffer the entire BLOB into memory which can cause scalability issues or even OutOfMemoryExceptions
               using (SqlDataReader dr = awaitcmd.ExecuteReaderAsync(CommandBehavior.SequentialAccess)) {
                  if (await dr.ReadAsync())
                  {
                     if (!(await dr.IsDBNullAsync(0))) 
                     {  // 欄位不為空,就產生檔案
                        using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write)) {
                           using (Stream data = dr.GetStream(0)) 
                           {  // Asynchronously copy the stream from the server to the file we just created
                              await data.CopyToAsync(file);
                           }
                        }
                     }
                  }
               }
            }
         }
      }

      // Application transferring a large BLOB to SQL Server in .Net 4.5
      private static async Task StreamBLOBToServer() 
      {
         using (SqlConnection conn = new SqlConnection("DB連結字串")) {
            await conn.OpenAsync();

            using (SqlCommand cmd = new SqlCommand("INSERT INTO [BinaryStreams] (bindata) VALUES (@bindata)", conn)) {
               using (FileStream file = File.Open("二進位檔案的檔名", FileMode.Open)) {

                  // Add a parameter which uses the FileStream we just opened
                  // Size is set to 
-1 to indicate "MAX"
                  cmd.Parameters.Add("@bindata", SqlDbType.Binary, -1).Value = file;

                  await cmd.ExecuteNonQueryAsync();
               }
            }
         }
      }

如果需要VB語法,可以透過這個網站轉換語法 ( C# 轉成 VB )

http://codeconverter.sharpdevelop.net/SnippetConve...

相關文章:

[.ashx檔?泛型處理常式?]基礎入門#5....ADO.NET 與 將DB裡面的二進位圖片還原 (範例下載 & 大型控制項的ImageField)

https://www.dotblogs.com.tw/mis2000lab/2014/05/19/...

[.ashx檔?泛型處理常式?]基礎入門#5-1....ADO.NET 與 將DB裡面的二進位圖片還原 (FileUpload的 FileContent屬性 & FileBytes屬性)

https://www.dotblogs.com.tw/mis2000lab/2014/09/15/...

 
 

我將思想傳授他人, 他人之所得,亦無損於我之所有;

猶如一人以我的燭火點燭,光亮與他同在,我卻不因此身處黑暗。----Thomas Jefferson

......... 寫信給我,mis2000lab (at) yahoo.com.台灣 .....................................................................................

................   facebook社團   https://www.facebook.com/mis2000lab   ............................

................   Google+   https://plus.google.com/100202398389206570368/posts ..............

................  YouTube (ASP.NET) 線上教學影片  http://goo.gl/rGLocQ

arrow
arrow
    全站熱搜

    MIS2000 Lab 發表在 痞客邦 留言(0) 人氣()