使用C#调用Google Drive API时Files.Get触发NullReferenceException异常
解决Google Drive API移动表格时的NullReferenceException问题
我的项目需要实现以下功能:创建电子表格、填充内容、将表格移动到指定文件夹并锁定。目前创建和填充表格的功能正常,但执行移动文件操作时,在代码行var getRequest = DriveService.Files.Get(fileId);处抛出以下异常:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
相关代码如下:
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(); }
问题根源
你在Init方法中创建的DriveService是局部变量,而MoveSheet方法中引用的是类的静态DriveService成员(从代码中SheetsService的使用方式可推断),这导致MoveSheet里的DriveService未被初始化,始终为null,从而触发空引用异常。
修复步骤
- 确保类级别声明了静态的
DriveService成员,与SheetsService对应:
// 在类的顶部添加静态成员声明 private static SheetsService SheetsService; private static DriveService DriveService;
- 修改
Init方法中的代码,将局部的DriveService赋值改为给静态成员赋值,去掉局部变量的声明:
// Create a Drive API service client DriveService = new DriveService(new Google.Apis.Services.BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = ApplicationName, });
完成以上修改后,MoveSheet方法就能正确引用到已初始化的DriveService实例,避免空引用异常。
内容的提问来源于stack exchange,提问作者warrenk
相关产品推荐
相关产品推荐

