使用Google Drive API v3下载的文件具有不同的内容

时间:2017-05-19 23:19:22

标签: c# api file url google-drive-api

我第一次使用Google Drive API,我需要下载一个简单的txt文件,该文件只包含一行版本号(如2.5.1.0),但是当我下载时文件并打开它,我得到了完全不同的东西。

另外,如果我只是使用任何浏览器下载文件,它会有预期的内容,但是当我通过我的应用程序下载时却没有。

对此我有任何建议。

到目前为止,这是我的代码:

private void CheckForUpdates()
    {
        GoogleDrive drive = new GoogleDrive();
        string url = drive.GetFileURL("current.txt");
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);

        string tmpPath = Path.Combine(Path.GetTempPath(), "current.txt");
        request.Timeout = 5000;
        WebClient response = new WebClient();
        response.DownloadFile(url, tmpPath);
    }

public string GetFileURL(string fileName)
    {
        DriveService service = GetDriveService();
        // Define parameters of request.
        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = 10;
        listRequest.Fields = "nextPageToken, files(id, name, parents, properties, shared, webContentLink, webViewLink, fullFileExtension, capabilities)";
        listRequest.Q = string.Format("(name contains '{0}')", fileName);
        IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
        if (files.Count > 0)
        {
            string url = files[0].WebContentLink;
            string id = files[0].Id;                  
            return url;
        }
        return "";
    }


private DriveService GetDriveService()
    {
        UserCredential credential;
         DriveService service;
        using (var stream = new FileStream(_pathClave, FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            credPath = _pathResult;
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }

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

        return service;
    }

这是链接:https://drive.google.com/uc?id=0B3P8S21qYracclVaamM2Skp4bzA&export=download

1 个答案:

答案 0 :(得分:0)

        Imports System.Net
        Imports System.ComponentModel

        Dim Str As IO.Stream
        Dim srRead As IO.StreamReader
        Dim NewVer As String = ""
        Dim req As WebRequest = WebRequest.Create("WebContentLink")

        Dim resp As WebResponse = req.GetResponse
        Str = resp.GetResponseStream
        srRead = New IO.StreamReader(Str)
        NewVer = srRead.ReadToEnd.Trim

vb代码对我有用可能有帮助