2017-02-22 5 views
3

Как загрузить файл на Google диск с заданным почтовым адресом с помощью C#?Загрузить файл на Google Диск с помощью C#

+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

Не уверен, что вы имели в виду под «upload with mail ID». Для доступа к Google Диску вам нужно будет получить токен доступа из Google для этой учетной записи. Это делается с использованием API.

Токен доступа будет возвращен после получения согласия пользователя; И этот токен доступа используется для отправки запросов API. Подробнее о Authorization

Для начала, вы должны включить свой Drive 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. 

Ниже приведен пример рабочего кода для загрузки на Диск.

// _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"); 
    } 
} 

Вот маленькую функцию для определения MimeType:

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: приветствую друга :). .. Я тоже должен тебе ... Это были действительно хорошие учебники там. Грасиас! ;) –

Смежные вопросы