2017-02-22 108 views
3

如何使用C#將文件上傳到帶有給定郵件地址的谷歌驅動器?使用C#將文件上傳到Google Drive#

+1

http://www.daimto.com/google-drive-api-c-upload/ – NicoRiff

+0

您無法真正使用電子郵件地址執行此操作,您必須通過用戶帳戶進行身份驗證才能訪問其數據。除此之外,答案中的代碼和上面的鏈接應該讓你開始。 – DaImTo

回答

2

除了@ 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

2

不確定你的意思是「用郵件上傳ID」。要訪問用戶的Google雲端硬盤,您必須從Google接收該帳號的訪問令牌。這是通過使用API完成的。

訪問令牌將在收到用戶的同意後返回;此訪問令牌用於發送API請求。瞭解更多關於Authorization

一開始,你必須使你的驅動器API,註冊您的項目,並從Developer Consol

獲取您的證書,那麼你可以用下面的代碼recieving用戶的同意,並獲得認證驅動器服務

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 recieved, your token will be stored locally on the AppData directory, so that next time you wont 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

+0

這是最新的https://github.com/LindaLawton/Google-Dotnet-Samples/tree/Genreated-samples1.0/Drive%20API – DaImTo

+0

另外,你可能想提及,他不能只使用他的電子郵件地址需要被認證。感謝您的鏈接btw :) – DaImTo

+1

@DaImTo:不客氣的朋友:)。 ..我也欠你一個...那些在那裏的一些非常好的教程..格拉西亞斯! ;) –

相關問題