Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

.net - Downloaded Google Drive Files corrupted c#

I am writing a program to download all the data in my Google Drive and save it. The problem is that when the file is saved, it's original size increases (for example, one .xls file which size it's 287KB it's saved as a 87411KB size) and I cannot open it because it says it is corrupt. Most of the files are .xls and .xlsx files.

I followed this tutorial plus the Google API documentation.

Right now I'm using the following code:

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();
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like your not resting the memory stream. Try moving var jetStream = new System.IO.MemoryStream(); into the 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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...