2017-02-22 20 views
3

Googleドライブにファイルをアップロードするには、特定のメールアドレスでC#を使用しますか?CドライブでGoogleドライブにファイルをアップロードする

+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

から資格情報を取得する必要がありドライブサービス

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. 

次は、ドライブにアップロードするためのコードです。

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

// _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タイプを決定するための少しの機能があります。

+0

これは最新のものですhttps://github.com/LindaLawton/Google-Dotnet-Samples/tree/Genreated-samples1.0/Drive%20API – DaImTo

+0

また、メールアドレスを使用することはできません認証する必要があります。リンクありがとうbtw :) – DaImTo

+1

@DaImTo:あなたは大歓迎です:)。 ..私もあなたに1つ借りている...それらは本当に素敵なチュートリアルだった。そこの..グラシアス! ;) –

関連する問題