My overall project is to create a spreadsheet, populate it, move it to a new location and lock it.
So far creating the sheet and populating it is fine. However, when I attempt to move the file I get the following error:
Happens at this part of the code: var getRequest = DriveService.Files.Get(fileId);
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
My code is:
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();
}