Follow this article to update all fields in DOC with C# REST API. You will learn how to update field in Word with C# Low Code API using a .NET-based Cloud SDK. A complete process will be demonstrated, starting from loading the source Word file and finally downloading the updated Word file from the Cloud storage.
Prerequisite
- Create an account and get API credentials
- Download Aspose.Words Cloud SDK for Dotnet for updating all fields
- Setup C# project with the above SDK for updating TOC and other fields
Steps to Update Field in Word with C# RESTful Service
- Instantiate the Configuration object by setting the Client secret and ID for updating fields
- Create the WordsApi object using the above configuration
- Load the source Word file into a memory stream with some field data such as TOC in it
- Create the UpdateFieldsOnlineRequest class to create a request for the loaded Word file
- Invoke the UpdateFieldsOnline() method using the above request object
- Parse the API response and access the returned stream
- Save the output stream as a file on the disk
The above steps explain how to update all fields in Word with C# REST API. Read the source Word file into the memory stream, create a request object, define the destination file name, and call the UpdateFieldsOnline() method to update fields. Parse the resultant stream in the response document and save it as a file on the disk.
Code to Automatically Update Fields in Word with C# REST API
using Aspose.Words.Cloud.Sdk; | |
using Aspose.Words.Cloud.Sdk.Model; | |
using Aspose.Words.Cloud.Sdk.Model.Requests; | |
using System; | |
using System.IO; | |
namespace WordsSample.Words | |
{ | |
public class WorkingWithFields | |
{ | |
public void UpdateAllFields() | |
{ | |
var apiClient = new Configuration(); | |
apiClient.ClientSecret = "Secret"; | |
apiClient.ClientId = "ID"; | |
var wordsApi = new WordsApi(apiClient); | |
using var requestDocument = File.OpenRead("SampleWithTOC.docx"); | |
var updateRequest = new UpdateFieldsOnlineRequest(requestDocument); | |
updateRequest.DestFileName = "output.docx"; | |
var task = wordsApi.UpdateFieldsOnline(updateRequest); | |
task.Wait(); var result = task.Result; | |
if (result.Document.TryGetValue("output.docx", out var stream)) | |
{ | |
stream.Position = 0; | |
using (var fileStream = File.Create("output.docx")) | |
{ | |
stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); | |
} | |
} | |
} | |
} | |
} |
This sample code demonstrates how to update Word fields in a Word file. You can update the table of contents, cross-references, page numbers, and date-time fields. When we set a destination file name, the returned document object contains a response with the same name to distinguish it from other files in the Cloud storage.
You may also check out another feature on the following page: Extract Text from Word Document with NET REST API.