调用百度云Api实现从百度云盘自动下载文件

                  一、注册账号

                要从百度云下载文件,首先,注册一个百度云账号,现在可能都要注册手机号啦,当然,如果你已经注册过,很幸运,就可以省略掉此步骤啦。

                  如图登录后所示:

                      点击Access Key,即显示上面的图示,创建的Access Key ID和Secret Access Key(点击显示与隐藏即可);或者点击“创建Access Key”,可以创建一个新的Access Key。

                      二、安装SDK工具包

                      这里提供一个链接,就是百度云的Api(https://cloud.baidu.com/doc/BOS/C-Dotnet-SDK.html#.E6.A6.82.E8.BF.B0),可以下载一个SDK直接添加引用,或在自己的VS项目中右击点击“管理Nuget程序包”->搜索“BceSdkDotNet.dll”安装即可。另外,记得第三方依赖工具包log4net.dllNewtonsoft.Json.dll也是需要添加的。

                    安装BceSdkDotNet.dll如下:  

                      代码如下:

using BaiduBce;
using BaiduBce.Auth;
using BaiduBce.Services.Bos;
using BaiduBce.Services.Bos.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBEN.ICEngine.BceSdkDotNet
{
    public static class FileDownLoadByBce
    {
        public static void FileDownLoad()
        {
            BosClient client = GenerateBosClient();
            const string bucketName = "/aaa";    //指定Bucket名称(文件夹名称)
            const string objectKey = "a.zip";     //指定object名称(文件名字)// 获取Object
            BosObject bosObject = client.GetObject(bucketName, objectKey);
            // 获取ObjectMeta
            ObjectMetadata meta = bosObject.ObjectMetadata;
            // 获取Object的输入流
            Stream objectContent = bosObject.ObjectContent;
            // 处理Object
            FileStream fileStream = new FileInfo(objectKey).OpenWrite();      //指定下载文件的目录/文件名
            byte[] buffer = new byte[2048];
            int count = 0;
            while ((count = objectContent.Read(buffer, 0, buffer.Length)) > 0)
            {
                fileStream.Write(buffer, 0, count);
            }

            // 关闭流
            objectContent.Close();
            fileStream.Close();
        }

        private static BosClient GenerateBosClient()
        {
            const string accessKeyId = "bea84b49522e4b6bb31ee286b2716cf3"; // 您的Access Key ID
            const string secretAccessKey = ""; // 您的Secret Access Key
            const string endpoint ="www.baidu.com";        //指定Bucket所在区域域名

            // 初始化一个BosClient
            BceClientConfiguration config = new BceClientConfiguration();
            config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey);
            config.Endpoint = endpoint;

            return new BosClient(config);
        }
    }
}

                     建立百度云盘是需要付费的。。。就写到这里啦。

 

 

posted @ 2017-03-09 16:13  雪?  阅读(30271)  评论(1编辑  收藏  举报