How to Remove Custom Property Fields in C#, VB.NET

In our daily work, we may have the requirement to add custom properties with fields to a Word document. As is shown in the following Word document, I have created three custom property fields for easily inserting or updating information.

How to Remove Custom Property Fields in C#, VB.NET

However, a custom property field may lose its value if we don’t want to use it any more, or a custom field might be created with wrong information, in such cases, we can choose to delete these fields manually and programmatically. In this article, I’ll introduce a C# and VB.NET solution to remove custom property fields using Spire.Doc.

Detailed Steps

Step 1: Create a new instance of Spire.Doc.Document class and load the sample file with specified path.

Document doc = new Document();
doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);

Step 2: Get custom document properties object.

CustomDocumentProperties cdp = doc.CustomDocumentProperties;

Step 3: Use a for sentence and CustomDocumentProperties.Remove(string name) method to remove all custom property fields in the document.

for (int i = 0; i < cdp.Count; )
{
  cdp.Remove(cdp[i].Name);
}
doc.IsUpdateFields = true;

Step 4: Save the file.

doc.SaveToFile("Result.docx", FileFormat.Docx);

Output:

How to Remove Custom Property Fields in C#, VB.NET

Full Code:

C#
using Spire.Doc;
namespace RemoveProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);
            CustomDocumentProperties cdp = doc.CustomDocumentProperties;
            for (int i = 0; i < cdp.Count; )
            {
                cdp.Remove(cdp[i].Name);
            }
            doc.IsUpdateFields = true;
            doc.SaveToFile("Result.docx", FileFormat.Docx);
        }
    }
}
VB.NET
Imports Spire.Doc
Namespace RemoveProperties
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("FieldSample.docx", FileFormat.Docx)
			Dim cdp As CustomDocumentProperties = doc.CustomDocumentProperties
			Dim i As Integer = 0
			While i < cdp.Count
				cdp.Remove(cdp(i).Name)
			End While
			doc.IsUpdateFields = True
			doc.SaveToFile("Result.docx", FileFormat.Docx)
		End Sub
	End Class
End Namespace