简体   繁体   中英

How to download file from google drive in c#?

I am trying to download file from Google Drive using ASPSnippets.GoogleAP.dll and Google.Apis.Drive.v3.dll . But facing some challenges. File is being downloaded, but it is in some type of weird HTML content.

I am using following code to download it :

GoogleConnect.ClientId = "xxxx.apps.googleusercontent.com";
GoogleConnect.ClientSecret = "xxxxxx";
GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
GoogleConnect.API = EnumAPI.Drive;
if (!string.IsNullOrEmpty(Request.QueryString["code"]))
    {
     string code = Request.QueryString["code"];
     string json = GoogleConnect.Fetch("me", code);
     GoogleDriveFiles files = new JavaScriptSerializer().Deserialize<GoogleDriveFiles>(json);

     //Remove the deleted files.
     var driveService = new DriveService();
     Label1.Text = theHiddenField1.Value;
     WebClient wb = new WebClient();
     wb.DownloadFile(theHiddenField1.Value, "C://" + fileName);
    }
    else if (Request.QueryString["error"] == "access_denied")
     { 
       ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);                           
     }
      else
      {   
        GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.readonly");              
       }  

Can someone please help me to resolve the issue?

I'm not a C# developer, but if you're using Google.Apis.Drive.v3 , then that is the latest version of the Google Drive API . I don't see any part of your code that references the Google APIs Client Library for .NET , but that's the recommended way to talk to modern Google APIs.

If you've installed it, take a look at the C# quickstart sample for the Drive API . Then check out the C#/.NET examples on the Download Files page in the docs, and it should lead you to a working solution. In your other comment, you asked about passing auth tokens, so if you're using the client library, you shouldn't have to worry about that part. On that docs page, you'll find a sample for regular file downloads and another for exporting Google documents (Docs, Sheets, Slides).

Finally, for additional reference, here are the .NET reference docs for the Drive API and the .NET Google APIs Client Library developers guide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM