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

今天在MSDN上找到好範例,

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

 

首先,您可以從這篇文章,瞭解「非同步」在做些什麼?

.NET 4.5 非同步程式,從一張圖知道原來如此 (async & await)
https://dotblogs.com.tw/mis2000lab/2016/03/10/net45_easy_async_concept

.............................................................................................................................................

 

MSDN範例來源: https://msdn.microsoft.com/zh-tw/library/hh556234(v=vs.110).aspx

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

除了二進位檔案(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 = await cmd.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/SnippetConverter.aspx

 

相關文章:

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

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

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

https://www.dotblogs.com.tw/mis2000lab/2014/09/15/ashx_beginner_05-1_db_picture_show_download

 

 

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

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

線上課程教學,遠距教學 (Web Form 約 51hr)  https://dotblogs.com.tw/mis2000lab/2016/02/01/aspnet_online_learning_distance_education_VS2015

線上課程教學,遠距教學 (ASP.NET MVC 約 135hr)  https://dotblogs.com.tw/mis2000lab/2018/08/14/ASPnet_MVC_Online_Learning_MIS2000Lab

 

寫信給我,不要私訊 --  mis2000lab (at) yahoo.com.tw  或  school (at) mis2000lab.net

 (1) 第一天 ASP.NET MVC5 完整影片(5.5小時 / .NET 4.x版)免費試聽。影片 https://youtu.be/9spaHik87-A 

 (2) 第一天 ASP.NET Core MVC 完整影片(3小時 / .NET Core 6.0~8.0)免費試聽。影片 https://youtu.be/TSmwpT-Bx4I 

[學員感言] mis2000lab課程評價 - ASP.NET MVC , WebForm  。 https://mis2000lab.medium.com/%E5%AD%B8%E5%93%A1%E6%84%9F%E8%A8%80-mis2000lab%E8%AA%B2%E7%A8%8B%E8%A9%95%E5%83%B9-asp-net-mvc-webform-77903ce9680b  


ASP.NET遠距教學、線上課程(Web Form + MVC)。 第一天課程, "完整" 試聽。 

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

.........  YouTube (ASP.NET) 線上教學影片  https://www.youtube.com/channel/UC6IPPf6tvsNG8zX3u1LddvA/

 

Blog文章 "附的範例" 無法下載,請看 https://dotblogs.com.tw/mis2000lab/2016/03/14/2008_2015_mis2000lab_sample_download

請看我們的「售後服務」範圍(嚴格認定)。

...................................................................................................................................................... 

ASP.NET MVC  => .NET Core MVC 線上教學  ...... 第一天課程 完整內容 "免費"讓您評估 / 試聽

[遠距教學、教學影片] ASP.NET (Web Form) 課程 上線了!MIS2000Lab.主講   事先錄好的影片,並非上課側錄!   觀看時,有如「一對一」面對面講課