首页 > 解决方案 > c# google drive上传文件

问题描述

嗨,我想上传文件谷歌驱动器,但每次,我都有这个错误对象引用未设置为对象的实例。我确实认为这个视频系列链接。我接受了谷歌驱动器上传请求。我尝试了 zip 、 jpg 、 txt 上传但同样的错误。我尝试了 Google.Apis.Drive.v2 但同样的错误。我能做些什么?请帮助对不起我的英语:(

private static string ApplicationName = "MysqlYedekleme";
    private static string FolderId = "1g_PTi5lQBCbZBax_3foZPdiECOC7cSaU";
    private static string filename = "test.rar";
    private static string filePath = @"E:\yedekdeneme\test.rar";
    private static string contentType = "application/zip";
    //drve
    private void Form1_Load(object sender, EventArgs e)
    {
        UserCredential credential = GetUserCredential();
        DriveService service = GetDriveService(credential);
        uploadFileDrive(service, filename, filePath, contentType);
    }

    private static UserCredential GetUserCredential()
    {
        using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string creadPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            creadPath = Path.Combine(creadPath, "driveApiCredentials", "drive-credentials.json");
            return GoogleWebAuthorizationBroker.AuthorizeAsync(

                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "User",
                CancellationToken.None,
                new FileDataStore(creadPath, true)).Result;

        }
    }

    private static DriveService GetDriveService(UserCredential credential)
    {
        return new DriveService
            (new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

    }
    private static string uploadFileDrive(DriveService service, string filename, string filePath, string contentType)
    {

        try
        {
           var fileMetadata = new Google.Apis.Drive.v3.Data.File();
        fileMetadata.Name = Path.GetFileName(filePath);
        fileMetadata.MimeType = "application/zip";
                  fileMetadata.Parents = new List<string> { FolderId };

        FilesResource.CreateMediaUpload request;
        using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
        {
            request = service.Files.Create(fileMetadata, stream, contentType);
            request.Fields = "id";
            request.Upload();
        }
        var file = request.ResponseBody;
        return file.Id;
        }
        catch (Exception exc)
        {

            System.Diagnostics.Debug.WriteLine("geldi:"+exc.Message);
        }


    }

标签: c#.netgoogle-apigoogle-drive-apigoogle-api-dotnet-client

解决方案


推荐阅读