#c# #.net #google-api #google-drive-api #google-api-dotnet-client
#c# #.net #google-api #google-drive-api #google-api-dotnet-client
Вопрос:
Я пишу программу для загрузки всех данных с моего Google Диска и сохранения их. Проблема в том, что при сохранении файла его исходный размер увеличивается (например, один файл .xls, размер которого составляет 287 КБ, сохраняется как размер 87411 КБ), и я не могу его открыть, потому что он говорит, что он поврежден. Большинство файлов представляют собой файлы .xls и .xlsx.
Я следовал этому руководству, а также документации Google API.
Прямо сейчас я использую следующий код:
public static void GetFilesFromDrive()
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Resu<
Console.WriteLine("Credential file saved to: " credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 400;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine("Files:");
String path = copypath;
var jetStream = new System.IO.MemoryStream();
if (files != null amp;amp; files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
FilesResource.GetRequest request = new FilesResource.GetRequest(service, file.Id);
//ExportRequest(service, file.Id, "application/vnd.google-apps.file");
//(service, file.Id);
string pathforfiles = path file.Name.ToString();
request.MediaDownloader.ProgressChanged = (Google.Apis.Download.IDownloadProgress progress) =>
{
switch (progress.Status)
{
case Google.Apis.Download.DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case Google.Apis.Download.DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
using (System.IO.FileStream file = new System.IO.FileStream(pathforfiles, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
jetStream.WriteTo(file);
}
break;
}
case Google.Apis.Download.DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request.DownloadWithStatus(jetStream);
}
}
else
{
Console.WriteLine("No files found.");
}
//Console.Read();
}
Комментарии:
1.
jetStream
кажется, это одинMemoryStream
объект, в который вы направляете каждую загрузку для записи.
Ответ №1:
Похоже, вы не успокаиваете поток памяти. Попробуйте перейти var jetStream = new System.IO.MemoryStream();
на передний план.
if (files != null amp;amp; files.Count > 0)
{
foreach (var file in files)
{
var jetStream = new System.IO.MemoryStream();
Console.WriteLine("{0} ({1})", file.Name, file.Id);
FilesResource.GetRequest request = new FilesResource.GetRequest(service, file.Id);
//ExportRequest(service, file.Id, "application/vnd.google-apps.file");
//(service, file.Id);
string pathforfiles = path file.Name.ToString();
request.MediaDownloader.ProgressChanged = (Google.Apis.Download.IDownloadProgress progress) =>
{
switch (progress.Status)
{
case Google.Apis.Download.DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case Google.Apis.Download.DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
using (System.IO.FileStream file = new System.IO.FileStream(pathforfiles, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
jetStream.WriteTo(file);
}
break;
}
case Google.Apis.Download.DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request.DownloadWithStatus(jetStream);
}
}