2017-02-22 3 views
3

주어진 메일 주소로 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

"메일 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. 

다음은 드라이브에 업로드하기위한 코드입니다.

// _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 : 당신은 오신 것을 환영합니다 친구 :). .. 나도 너 한테 빚 졌어.저기서 정말 멋진 자습서 였어. 그레시아! ;) –

관련 문제