首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 將 Base64 字串儲存為本地檔案完整實作 (含資料庫 Blob 讀取範例)

     編輯:關於C#

核心方法:Base64 字串存檔

public void SaveBase64ToFile(string base64Content, string fileName)
{
    if (string.IsNullOrEmpty(base64Content)) throw new ArgumentException("內容不可為空", nameof(base64Content));
    if (string.IsNullOrEmpty(fileName)) throw new ArgumentException("檔名不可為空", nameof(fileName));

    byte[] data;
    try
    {
        data = Convert.FromBase64String(base64Content);
    }
    catch (FormatException ex)
    {
        throw new ArgumentException("非有效 Base64 字串", nameof(base64Content), ex);
    }

    string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);

    // 確保目錄存在
    string dir = Path.GetDirectoryName(fullPath);
    if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
        Directory.CreateDirectory(dir);

    using (var fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
    {
        fs.Write(data, 0, data.Length);
        fs.Flush(); // 確保寫入磁碟
    }
}

資料庫 Blob (byte[]) 讀取並存檔

public void SaveBlobFromDatabase(string connectionString, string query, string outputFileName)
{
    using (var conn = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(query, conn))
    {
        conn.Open();
        // 假設查詢回傳單一資料列、單一欄位 (varbinary/varbinary(max))
        object result = cmd.ExecuteScalar();
        if (result == null || result == DBNull.Value)
        {
            Console.WriteLine("資料庫無資料");
            return;
        }

        byte[] blob = (byte[])result;
        string base64 = Convert.ToBase64String(blob); // 轉 Base64 字串
        SaveBase64ToFile(base64, outputFileName);
        Console.WriteLine($"已儲存至 {Path.Combine(AppDomain.CurrentDomain.BaseDirectory, outputFileName)}");
    }
}

資料庫儲存 Blob 範例 (參考)

public void SaveFileToDatabase(string connectionString, string filePath)
{
    byte[] data = File.ReadAllBytes(filePath);
    string base64 = Convert.ToBase64String(data);

    using (var conn = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand("INSERT INTO Files (FileName, Content) VALUES (@name, @content)", conn))
    {
        cmd.Parameters.AddWithValue("@name", Path.GetFileName(filePath));
        // 直接存 byte[] 更有效率,這裡示範 Base64 字串欄位
        cmd.Parameters.AddWithValue("@content", base64);
        conn.Open();
        cmd.ExecuteNonQuery();
    }
}

關鍵點提醒

  • Convert.FromBase64String 會忽略空白字元 (換行、空格),但不接受非 Base64 字元。
  • 大檔案記憶體壓力: Base64 編碼後體積膨脹 ~33%,若檔案 > 100MB 建議改用串流式 Base64 解碼 (System.IO.Compression 或第三方庫) 避免一次性配置大陣列。
  • 資料庫欄位型別: 直接存 varbinary(max) 比存 Base64 字串節省空間且效能更好;Base64 適用於 JSON/XML 傳輸、文字型欄位。
  • 路徑處理: 使用 Path.Combine 與 AppDomain.CurrentDomain.BaseDirectory 確保跨平台相容。

資料庫 Blob 內容示意圖

參考資源

原文連結:https://www.bianceng.cn/Programming/csharp/201410/45587.htm

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved