Skip to content

Instantly share code, notes, and snippets.

@jedjohan
Created February 2, 2019 09:04
Show Gist options
  • Save jedjohan/fb121ca43bb83dd76b0c1f03804c0335 to your computer and use it in GitHub Desktop.
Save jedjohan/fb121ca43bb83dd76b0c1f03804c0335 to your computer and use it in GitHub Desktop.

Revisions

  1. jedjohan created this gist Feb 2, 2019.
    53 changes: 53 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    using System;
    using System.Collections.Generic;
    using System.IO;
    using Microsoft.Office.Interop.Word;

    class Program
    {
    static void Main(string[] args)
    {
    List<string> path = new List<string>(args);
    string filePath = string.Join(" ", path.ToArray());
    string folderPath = Path.GetDirectoryName(filePath);

    try
    {
    Application ap = new Application();
    Document document = ap.Documents.Open(filePath);
    document.Fields.Update();

    foreach (Section section in document.Sections)
    {
    document.TrackRevisions = false;
    HeadersFooters headers = section.Headers; //Get all headers
    foreach (HeaderFooter header in headers)
    {
    Fields fields = header.Range.Fields;
    foreach (Field field in fields)
    {
    // Här har du fälten i headern. Kolla om det är den du vill uppdatera. Tex
    if (field.Type == Microsoft.Office.Interop.Word.WdFieldType.wdFieldUserName)
    {
    field.Select();
    field.Delete();
    document.Selection.TypeText("Johan Eriksson");
    }

    // Osv med uppdateringar

    field.Update();
    }
    }
    }

    document.Save();
    document.Close();

    }
    catch (NullReferenceException)
    {
    System.Windows.Forms.MessageBox.Show("A valid file was not selected.");
    }
    }
    }