下载 Google 驱动器文件已损坏 c#

Downloaded Google Drive Files corrupted c#

我正在编写一个程序来下载我的 Google 驱动器中的所有数据并保存。问题是当文件被保存时,它的原始大小增加了(例如,一个大小为 287KB 的 .xls 文件被保存为 87411KB 大小)并且我无法打开它,因为它说它已损坏。大多数文件是 .xls 和 .xlsx 文件。

我遵循了 this 教程和 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)).Result;
                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 && 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();
        }

看起来你没有休息内存流。尝试将 var jetStream = new System.IO.MemoryStream(); 移动到 foreach。

if (files != null && 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);
    }
}