1. 程式人生 > >C# 讀取Stream流檔案並儲存到本地

C# 讀取Stream流檔案並儲存到本地

Stream stream = fileBLL.DownloadFile(fileInfo); //獲取檔案流
byte[] srcBuf = new Byte[stream.Length];
stream.Read(srcBuf, 0, srcBuf.Length);
stream.Seek(0, SeekOrigin.Begin);  

//判斷路徑是否正確
if (string.IsNullOrEmpty(filePath))
{
    return false;
}
else
{
    try //確保目錄存在
    {
        if (string.IsNullOrEmpty(folderPath))
        {
                return false;
        }
        if (Directory.Exists(folderPath))
        {
                return true;
        }
        else
        {
            try
            {
                return Directory.CreateDirectory(folderPath) != null;
            }
            catch(Exception ex)
            {
                Debug.WriteLine("建立資料夾失敗:" + ex.Message);
                return false;
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("生成檔案資訊物件失敗:" + ex.Message);
        return false;
    }
}

//儲存檔案到本地
try
{
    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
    {
        fs.Write(buf, 0, buf.Length);
        fs.Close();
    }

    return true;
}
catch (Exception ex)
{
    Debug.WriteLine(string.Format("寫入檔案出錯:訊息={0},堆疊={1}", ex.Message, ex.StackTrace));
    return false;
}