// Create a Google Ads client.GoogleAdsClientclient=newGoogleAdsClient();// Create the required service.CampaignServiceClientcampaignService=client.GetService(Services.V21.CampaignService);// Make more calls to service class.
建立 GoogleAdsClient 執行個體
Google Ads API .NET 程式庫中最重要的類別是 GoogleAdsClient 類別。您可以使用這個類別建立預先設定的服務類別,用於發出 API 呼叫。GoogleAdsClient 提供預設建構函式,可使用應用程式 App.config / Web.config 中指定的設定建立使用者物件。如需設定選項,請參閱設定指南。
// Create a new GoogleAdsClient with the App.config settings.GoogleAdsClientuser=newGoogleAdsClient();
建立服務
GoogleAdsClient 提供 GetService 方法,可用於建立 Google Ads 服務。
CampaignServiceClientcampaignService=client.GetService(Services.V21.CampaignService);// Now make calls to CampaignService.
我們提供 Services 類別,列舉所有支援的 API 版本和服務。建立服務時,GetService 方法會將這些列舉物件做為引數。舉例來說,如要為 Google Ads API 的 V21 版本建立 CampaignServiceClient 執行個體,您需要使用 Services.V21.CampaignService 做為引數呼叫 GoogleAdsClient.GetService 方法,如上一個範例所示。
GoogleAdsClientclient1=newGoogleAdsClient();GoogleAdsClientclient2=newGoogleAdsClient();ThreaduserThread1=newThread(addAdGroups);ThreaduserThread2=newThread(addAdGroups);userThread1.start(client1);userThread2.start(client2);userThread1.join();userThread2.join();publicvoidaddAdGroups(objectdata){GoogleAdsClientclient=(GoogleAdsClient)data;// Do more operations here....}
避免 .NET Framework 應用程式凍結
同步方法可能會導致部分 .NET Framework 應用程式凍結。常見的例子是從 WinForm 應用程式的事件處理常式方法發出 API 呼叫。
並非每次 API 呼叫都會成功。如果 API 呼叫因故失敗,伺服器可能會擲回錯誤。請務必擷取 API 錯誤並妥善處理。
發生 API 錯誤時,系統會擲回 GoogleAdsException 例項。這份報告包含詳細資料,可協助您找出問題:
// Get the CampaignService.CampaignServiceClientcampaignService=client.GetService(Services.V21.CampaignService);// Create a campaign for update.CampaigncampaignToUpdate=newCampaign(){ResourceName=ResourceNames.Campaign(customerId,campaignId),// More fields to update.// ...};// Create the operation.CampaignOperationoperation=newCampaignOperation(){Update=campaignToUpdate,UpdateMask=FieldMasks.AllSetFieldsOf(campaignToUpdate)};try{// Update the campaign.MutateCampaignsResponseresponse=campaignService.MutateCampaigns(customerId.ToString(),newCampaignOperation[]{operation});// Display the results.// ...}catch(GoogleAdsExceptione){Console.WriteLine("Failure:");Console.WriteLine($"Message: {e.Message}");// Can examine to get more error details.Console.WriteLine($"Failure: {e.Failure}");// Can be shared with Google for further troubleshooting.Console.WriteLine($"Request ID: {e.RequestId}");}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-05 (世界標準時間)。"],[[["\u003cp\u003eThe Google Ads API client library for .NET will no longer support .NET 5.0 starting with version 19.0.0; upgrade to a newer .NET version before the end of 2024.\u003c/p\u003e\n"],["\u003cp\u003eInstall the client library using NuGet by adding a reference to the \u003ccode\u003eGoogle.Ads.GoogleAds\u003c/code\u003e package.\u003c/p\u003e\n"],["\u003cp\u003eAuthorize your API calls by providing client ID, client secret, refresh token, and developer token; guides are provided to obtain or generate these credentials.\u003c/p\u003e\n"],["\u003cp\u003eCreate a \u003ccode\u003eGoogleAdsClient\u003c/code\u003e instance and use its \u003ccode\u003eGetService\u003c/code\u003e method to create service classes for making API calls to various Google Ads services.\u003c/p\u003e\n"],["\u003cp\u003eHandle potential API errors by implementing error handling logic, catching \u003ccode\u003eGoogleAdsException\u003c/code\u003e to examine error details.\u003c/p\u003e\n"]]],[],null,["# Getting Started\n\nThis guide gives a brief overview of how to get started with the Google Ads API\n.NET library.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nInstallation\n------------\n\nThe client library binaries are distributed using NuGet. Add a NuGet reference\nto the [`Google.Ads.GoogleAds`\npackage](//www.nuget.org/packages/Google.Ads.GoogleAds/) in your project to use\nthe client library.\n\nSet up authorization\n--------------------\n\nTo authorize your API calls, you need to specify your client ID, client secret,\nrefresh token, and developer token to the library.\n\n### If you need to generate credentials\n\n- Follow the [Developer token guide](/google-ads/api/docs/get-started/dev-token) to obtain your developer token, if you don't already have one.\n- Follow the [OAuth desktop app flow](/google-ads/api/docs/client-libs/dotnet/oauth-desktop) guide to generate a client ID, client secret, and refresh token.\n\n### If you already have credentials\n\n- Copy the `GoogleAdsApi` node and the `GoogleAdsApi` section under the `configSections` node from the [`App.config` file in\n GitHub](https://github.com/googleads/google-ads-dotnet/blob/HEAD/Google.Ads.GoogleAds.Extensions/src/App.config) into your `App.config` / `Web.config` file. If you used NuGet to install the package, these nodes will be automatically inserted into your `App.config` / `Web.config` file.\n- Include the developer token, the client ID, client secret, and refresh token in your app's `App.config` / `Web.config`.\n\nThe [`App.config`](https://github.com/googleads/google-ads-dotnet/blob/HEAD/Google.Ads.GoogleAds.Extensions/src/App.config)\nfile included in GitHub is well-documented, but you can also refer to the\n[Configuration guide](/google-ads/api/docs/client-libs/dotnet/configuration)\nto learn more as well as use alternate ways to configure the client library,\nsuch as environment variables.\n\nMake an API call\n----------------\n\nThe basic usage of the client library is as follows: \n\n // Create a Google Ads client.\n GoogleAdsClient client = new GoogleAdsClient();\n\n // Create the required service.\n CampaignServiceClient campaignService =\n client.GetService(Services.V21.CampaignService);\n\n // Make more calls to service class.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n### Create a GoogleAdsClient instance\n\nThe most important classes in the Google Ads API .NET library is the\n`GoogleAdsClient` class. It lets you create a pre-configured service class\nthat can be used for making API calls. `GoogleAdsClient` provides a default\nconstructor that creates a user object using the settings specified in your\napp's `App.config` / `Web.config`. Refer to the [Configuration\nguide](/google-ads/api/docs/client-libs/dotnet/configuration) for configuration\noptions. \n\n // Create a new GoogleAdsClient with the App.config settings.\n GoogleAdsClient user = new GoogleAdsClient();\n\n### Create a service\n\n`GoogleAdsClient` provides a `GetService` method that can be used to create an\nAds service. \n\n CampaignServiceClient campaignService = client.GetService(Services.V21.CampaignService);\n // Now make calls to CampaignService.\n\nWe provide a `Services` class that enumerates all the supported API versions and\nservices. The `GetService` method accepts these enumeration objects as argument\nwhen creating the service. For example, to create an instance of\n`CampaignServiceClient` for version `V21` of the Google Ads API,\nyou need to call `GoogleAdsClient.GetService` method with\n`Services.V21.CampaignService` as the argument, as shown\nin the previous example.\n\nThread safety\n-------------\n\nIt is not safe to share a `GoogleAdsClient` instance between multiple threads,\nsince the configuration changes you make on an instance in one thread might\naffect the services you create on other threads. Operations like obtaining\nnew service instances from a `GoogleAdsClient` instance and making calls to\nmultiple services in parallel are thread-safe.\n\nA multithreaded application would look something like this: \n\n GoogleAdsClient client1 = new GoogleAdsClient();\n GoogleAdsClient client2 = new GoogleAdsClient();\n\n Thread userThread1 = new Thread(addAdGroups);\n Thread userThread2 = new Thread(addAdGroups);\n\n userThread1.start(client1);\n userThread2.start(client2);\n\n userThread1.join();\n userThread2.join();\n\n public void addAdGroups(object data) {\n GoogleAdsClient client = (GoogleAdsClient) data;\n // Do more operations here.\n ...\n }\n\nAvoid freezes in .NET Framework applications\n--------------------------------------------\n\nSynchronous methods can cause some of your .NET Framework applications to\nfreeze. A common example is making API calls from an event handler method\nof a WinForm application.\n\nThere are two ways to address this issue:\n\n1. **Use the legacy Grpc library.**\n\n You can set the `UseGrpcCore` property of `GoogleAdsConfig` to use the\n legacy `Grpc.Core` library instead of the default `Grpc.Net.Client` library.\n This method has not been tested extensively on .NET Framework applications,\n so it might not solve the issue. Here is a sample snippet: \n\n GoogleAdsConfig config = new GoogleAdsConfig();\n config.UseGrpcCore = true;\n GoogleAdsClient client = new GoogleAdsClient(config);\n\n2. **Use asynchronous methods.**\n\n You can use asynchronous methods to avoid freezes. Here are some examples: \n\n ### SearchStream\n\n A call to `SearchStream()` is performed, and the results are\n populated into a list view. \n\n ```c#\n private async void button1_Click(object sender, EventArgs e)\n {\n // Get the GoogleAdsService.\n GoogleAdsServiceClient googleAdsService = client.GetService(\n Services.V21.GoogleAdsService);\n \n // Create a query that will retrieve all campaigns.\n string query = @\"SELECT\n campaign.id,\n campaign.name,\n campaign.network_settings.target_content_network\n FROM campaign\n ORDER BY campaign.id\";\n \n List items = new List();\n Task t = googleAdsService.SearchStreamAsync(customerId.ToString(), query,\n delegate (SearchGoogleAdsStreamResponse resp)\n {\n foreach (GoogleAdsRow googleAdsRow in resp.Results)\n {\n ListViewItem item = new ListViewItem();\n item.Text = googleAdsRow.Campaign.Id.ToString();\n item.SubItems.Add(googleAdsRow.Campaign.Name);\n items.Add(item);\n }\n }\n );\n await t;\n listView1.Items.AddRange(items.ToArray());\n }\n ```\n\n ### Campaign Budget\n\n A CampaignBudget call is created, and the resource name of the new budget is\n displayed using a `MessageBox` alert. \n\n ```c#\n private async void button2_Click(object sender, EventArgs e)\n {\n // Get the BudgetService.\n CampaignBudgetServiceClient budgetService = client.GetService(\n Services.V21.CampaignBudgetService);\n \n // Create the campaign budget.\n CampaignBudget budget = new CampaignBudget()\n {\n Name = \"Interplanetary Cruise Budget #\" + ExampleUtilities.GetRandomString(),\n DeliveryMethod = BudgetDeliveryMethod.Standard,\n AmountMicros = 500000\n };\n \n // Create the operation.\n CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()\n {\n Create = budget\n };\n \n // Create the campaign budget.\n Task t = budgetService.MutateCampaignBudgetsAsync(\n customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });\n \n await t;\n MutateCampaignBudgetsResponse response = t.Result;\n MessageBox.Show(response.Results[0].ResourceName);\n }\n ```\n\n \u003cbr /\u003e\n\nError handling\n--------------\n\nNot every API call will succeed. The server can throw errors if your API calls\nfail for some reason. It is important to capture API errors and handle them\nappropriately.\n\nA `GoogleAdsException` instance is thrown when an API error occurs. It has\ndetails to help you figure out what went wrong: \n\n // Get the CampaignService.\n CampaignServiceClient campaignService = client.GetService(Services.V21.CampaignService);\n\n // Create a campaign for update.\n Campaign campaignToUpdate = new Campaign()\n {\n ResourceName = ResourceNames.Campaign(customerId, campaignId),\n // More fields to update.\n // ...\n };\n\n // Create the operation.\n CampaignOperation operation = new CampaignOperation()\n {\n Update = campaignToUpdate,\n UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)\n };\n\n try\n {\n // Update the campaign.\n MutateCampaignsResponse response = campaignService.MutateCampaigns(\n customerId.ToString(), new CampaignOperation[] { operation });\n\n // Display the results.\n // ...\n }\n catch (GoogleAdsException e)\n {\n Console.WriteLine(\"Failure:\");\n Console.WriteLine($\"Message: {e.Message}\");\n\n // Can examine to get more error details.\n Console.WriteLine($\"Failure: {e.Failure}\");\n\n // Can be shared with Google for further troubleshooting.\n Console.WriteLine($\"Request ID: {e.RequestId}\");\n }"]]