[Azure] C# + Azure.Storage.Blobs v12 - 建立 Container, 上傳檔案 , 列出資料 , 列出資料夾 , 刪除檔案 , 刪除檔案夾

2020-12-29

之前其實我寫過 Azure Storage Blob 手把手從頭開始 - 建立檔案夾和檔案 , 但是那時候用的 nuget library Microsoft.Azure.Storage.Blob (  https://www.nuget.org/packages/Microsoft.Azure.Storage.Blob/ ) 已經要被停用了 ,現在都改用 Azure.Storage.Blobs ( https://www.nuget.org/packages/Azure.Storage.Blobs ) 差異在哪裡,在 namespace 少了 Microsoft 字樣,內部 API 也有寫許更動,設計邏輯感覺比較更成熟,之前 async 顯得略凌亂,這次 API 感覺使用起來 舒爽了些,然後跟 Stoarge Table 拆開了。




前置步驟,首先你得安裝新版的 Azure.Storage.Blobs ( https://www.nuget.org/packages/Azure.Storage.Blobs ) 12.7.0 ,不要裝到舊版的,這邊我撰寫案例是用 .net core 3.1


之後在 Azure Portal  開一個 儲存體帳戶,並且在左側的存取金鑰中拿到 Connection String.

1. 建立 Container ,這邊程式不難,而且有溫馨的 CreateIfNotExists



2. 上傳檔案,這邊就是很單純的上傳,之後文章我再來聊聊使用 ETag 上傳,這邊也直接很溫馨的使用 Upload , overrite : true



3. 列出檔案


Result:

images/girls/2020/samplex.jpg
images/girls/2020_TMP/samplex.jpg
images/girls/images.jpg
images/sample1.jpg
images/sample2.jpg
images/sample3.jpg
images/samplex.jpg
images2/sample1.jpg
images2/sample2.jpg
images2/sample3.jpg
images2/sample4.jpg
images2/sample5.jpg

      
4.列出檔案夾


Result:

/[DIRS]
          images/
          images2/
/images/[DIRS]
          images/girls/
/images/girls/[DIRS]
          images/girls/2020/
          images/girls/2020_TMP/


5.刪除檔案,在文中我指定刪除 images/girls/2020/samplex.jpg 的檔案


6.刪除檔案夾,這代表意思就是 只要是 prefix 開頭是 images/girls/2020_TMP/ 檔案全部刪除,當裡面沒有檔案後該資料夾也會不存在



最後,暫時先寫到這裡,應該基本操作都有了,最近要用到就乾脆重新寫這系列,如果有一些測試的心得,我也會繼續寫下去,其實中間有一些小的枚角,像是路徑前面或是後面的斜線都會影響到執行結果,官方案例寫的也不錯,只是有時候也會碰到一些小問題。


reference:

https://docs.microsoft.com/zh-tw/azure/storage/blobs/storage-blobs-list?tabs=dotnet


當麻許的超技八 2014 | Donma Hsu Design.