使用c#,我得到一个错误使用文件.获取Google Drive API



我的整体项目是创建一个电子表格,填充它,将它移动到一个新的位置,并锁定它。

到目前为止,创建工作表并填充它是没问题的。然而,当我试图移动文件时,我得到以下错误:
发生在代码的这一部分:var getRequest = DriveService.Files.Get(fileId);

系统。得到NullReferenceException
HResult x80004003 = 0
Message=对象引用未设置为对象的实例。

我的代码是:
static void Init()
{
UserCredential credential;
//Reading Credentials File...
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);               
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Creating Google Sheets API service...
SheetsService = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Create a Drive API service client
DriveService DriveService = new DriveService(new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
static void CreateSheet()
{
// Create a new sheet with a single tab
string sheetName = "Test Create Sheet";
var NewSheet = new Google.Apis.Sheets.v4.Data.Spreadsheet();
NewSheet.Properties = new SpreadsheetProperties();
NewSheet.Properties.Title = sheetName;

var newSheet = SheetsService.Spreadsheets.Create(NewSheet).Execute();
SpreadsheetId = newSheet.SpreadsheetId;
Sheet = "Sheet1";
}
static void MoveSheet()
{
// Get the ID of the sheet you want to move
string sheetId = SpreadsheetId;
// Get the ID of the folder you want to move the sheet to
string folderId = "XXXXXBeNF2rG0PA6bsi89YugahH-XXXX";
// Retrieve the existing parents to remove
string fileId = sheetId;
var getRequest = DriveService.Files.Get(fileId);
getRequest.Fields = "parents";
var file = getRequest.Execute();
var previousParents = String.Join(",", file.Parents);
// Move the file to the new folder
var updateRequest =
DriveService.Files.Update(new Google.Apis.Drive.v3.Data.File(),
fileId);
updateRequest.Fields = "id, parents";
updateRequest.AddParents = folderId;
updateRequest.RemoveParents = previousParents;
//file = updateRequest.Execute();
}

原来我有一个重复的单词(DriveService):

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

应该是这样的:

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

我现在已经解决了这个问题,并且有了一个新的形式:

业务驱动器抛出异常。HttpStatusCode是禁止的。权限不足:请求的身份验证范围不足。

相关内容

最新更新