c# - 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# - 使用 Bunit 的条件模拟数据(Moq)
- sas - 无法创建大于 40 的 xpt 文件 (Sas8) 标签
- html - CSS 文件未加载到 HTML 文件中。我正在使用 Netbeans IDE
- mysql - 在 NodeJS 中从 MySQL 查询发送 JSON?
- java - 涉及大量 Mysql 查询的 Java 代码的 JMH 基准测试
- css - 在 owl carousel 中为 card boostrap 添加边距
- dataframe - 如何修改火花中的特定列?
- javascript - Uncaught (in promise) TypeError: states.filter is not a function at searchStates
- snowflake-cloud-data-platform - 我们应该在交换表之前暂停雪花任务吗?
- python - Equivalent code from python apply function to Pyspark code using udf