使用C#将文件上传到Google云端硬盘

时间:2017-02-22 11:39:05

标签: c# google-drive-api

如何使用C#?

将文件上传到谷歌驱动器,使用给定的邮件地址

2 个答案:

答案 0 :(得分:6)

除了@NicoRiff的参考,您还可以查看此Uploading Files文档。这是一个示例代码:

var fileMetadata = new File()
{
    Name = "My Report",
    MimeType = "application/vnd.google-apps.spreadsheet"
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/report.csv",
                        System.IO.FileMode.Open))
{
    request = driveService.Files.Create(
        fileMetadata, stream, "text/csv");
    request.Fields = "id";
    request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);

您也可以查看tutorial

答案 1 :(得分:4)

不确定“使用邮件ID上传”是什么意思。要访问用户的Google云端硬盘,您必须从该特定帐户收到Google的访问令牌。这是使用API完成的。

在获得用户同意后,将返回访问令牌。此访问令牌用于发送API请求。详细了解Authorization

首先,您必须启用Drive API,注册项目并从Developer Console

获取凭据

然后,您可以使用以下代码获得用户的同意并获取经过身份验证的云端硬盘服务

string[] scopes = new string[] { DriveService.Scope.Drive,
                             DriveService.Scope.DriveFile};
var clientId = "xxxxxx";      // From https://console.developers.google.com
var clientSecret = "xxxxxxx";          // From https://console.developers.google.com
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId,
                                                                              ClientSecret = clientSecret},
                                                        scopes,
                                                        Environment.UserName,
                                                        CancellationToken.None,
                                                        new FileDataStore("MyAppsToken")).Result; 
//Once consent is received, your token will be stored locally on the AppData directory, so that next time you won't be prompted for consent. 

DriveService service = new DriveService(new BaseClientService.Initializer()
{
   HttpClientInitializer = credential,
   ApplicationName = "MyAppName",
});
service.HttpClient.Timeout = TimeSpan.FromMinutes(100); 
//Long Operations like file uploads might timeout. 100 is just precautionary value, can be set to any reasonable value depending on what you use your service for.

以下是用于上传到云端硬盘的工作代码。

    // _service: Valid, authenticated Drive service
    // _uploadFile: Full path to the file to upload
    // _parent: ID of the parent directory to which the file should be uploaded

public static Google.Apis.Drive.v2.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
{
   if (System.IO.File.Exists(_uploadFile))
   {
       File body = new File();
       body.Title = System.IO.Path.GetFileName(_uploadFile);
       body.Description = _descrp;
       body.MimeType = GetMimeType(_uploadFile);
       body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };

       byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
       System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
       try
       {
           FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
           request.Upload();
           return request.ResponseBody;
       }
       catch(Exception e)
       {
           MessageBox.Show(e.Message,"Error Occured");
       }
   }
   else
   {
       MessageBox.Show("The file does not exist.","404");
   }
}

这是确定文件MIME类型的小函数:

private static string GetMimeType(string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
        mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}

Source

相关问题