Over a million developers have joined DZone.

Find & Replace Text in Word Document Using REST API in .NET Application

DZone's Guide to

Find & Replace Text in Word Document Using REST API in .NET Application

· ·
Free Resource
This technical tip allows developers to replace text in Word document using Saaspose.Words REST API in your .NET applications.  Some important steps for performing this task are to build URI to replace text, serialize the JSON request content, set old string to replace, set new string to replace, Parse the json string to JObject, sign URI, get response stream and the ReplaceText class is also given in detail.
//build URI to replace text

string strURI = "http://api.saaspose.com/v1.0/words/input.docx/replaceText";
string signedURI = Sign(strURI);

//serialize the JSON request content
ReplaceText replacetext = new ReplaceText();

// set old string to replace
replacetext.OldValue = OldValue;

// set new string to replace
replacetext.NewValue = NewValue;

// True indicates case-sensitive comparison, false indicates case-insensitive comparision.

replacetext.IsMatchCase = IsMatchCase;

// True indicates the oldValue must be a standalone word.

replacetext.IsMatchWholeWord = IsMatchWholeWord;
string strJSON = JsonConvert.SerializeObject(replacetext);
Stream responseStream = ProcessCommand(signedURI, "POST", strJSON);
StreamReader reader = new StreamReader(responseStream);
string strResponse = reader.ReadToEnd();
//Parse the json string to JObject
JObject pJSON = JObject.Parse(strResponse);
ReplaceTextResponse baseResponse = JsonConvert.DeserializeObject
//sign URI
signedURI = Sign(baseResponse.DocumentLink.Href + "?format=doc");
//get response stream
responseStream = ProcessCommand(signedURI, "GET");
using (Stream fileStream = System.IO.File.OpenWrite(outputPath))
 CopyStream(responseStream, fileStream);

//Here is the ReplaceText class
public class ReplaceText
 public string OldValue { get; set; }
 public string NewValue { get; set; }
 public bool IsMatchCase { get; set; }
 public bool IsMatchWholeWord { get; set; }


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}