2

Весь код работает без ошибок, но когда я проверяю свою учетную запись Google Диска, я не могу найти файл, который я загружаю («document.txt»).Не удалось загрузить файл на Google Drive - с помощью C#

Также он снова спросил меня об аутентификации.

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    new ClientSecrets 
    { 
     ClientId = "Here my clientid", 
      ClientSecret = "client secret", 
    }, 
    new[] { DriveService.Scope.Drive }, 
    "user", 
    CancellationToken.None).Result; 

// Create the service. 
var service = new DriveService(new BaseClientService.Initializer() 
{ 
    HttpClientInitializer = credential, 
    ApplicationName = "Drive API Sample", 
}); 

File body = new File(); 
body.Title = "My document"; 
body.Description = "A test document"; 
body.MimeType = "text/plain"; 

byte[] byteArray = System.IO.File.ReadAllBytes("document.txt"); 
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); 

FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain"); 
request.Upload(); 

File file = request.ResponseBody; 

Вопросы: Почему я не могу найти свой закачанный файл, и как я могу это помнить мою проверку подлинности.

ответ

0

Я думаю, что вы забыли body.Parent, чтобы он не знал, в какую директорию помещать файл.

parents[] list Collection of parent folders which contain this file. Setting this field will put the file in all of the provided folders. On insert, if no folders are provided, the file will be placed in the default root folder.

пример:

body.Parents = new List<ParentReference>() { new ParentReference() { Id = 'root' } }; 

Вы получаете попросили для проверки подлинности снова, потому что вы не спасаете аутентификацию.

//Scopes for use with the Google Drive API 
string[] scopes = new string[] { DriveService.Scope.Drive, 
           DriveService.Scope.DriveFile}; 
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% 
UserCredential credential = 
      GoogleWebAuthorizationBroker 
          .AuthorizeAsync(new ClientSecrets { ClientId = CLIENT_ID 
                  , ClientSecret = CLIENT_SECRET } 
              ,scopes 
              ,Environment.UserName 
              ,CancellationToken.None 
              ,new FileDataStore("Daimto.GoogleDrive.Auth.Store") 
             ).Result; 

FileDataStore хранит данные аутентификации в каталоге% appdata%.

Более подробную информацию можно найти в учебнике Google Drive API with C# .net – Upload

Update Для следующей ошибки:

"The API is not enabled for your project, or there is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your configuration. [403]"

Перейти к консоли разработчика для проекта here Под APIs & Auth -> API-интерфейсы позволяют Google Drive API и sdk. Также перейдите к учетным данным и убедитесь, что вы добавили имя продукта и адрес электронной почты.

+0

Спасибо за ответ. Я сделаю предлагаемые изменения –

+0

Вы можете найти образец проекта, чтобы пройти по этому учебнику здесь https://github.com/LindaLawton/Google-Dotnet-Samples/tree/master/Google-Drive – DaImTo

+0

отлично. Дай мне проверить. –

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

  • Нет связанных вопросов^_^