1
\$\begingroup\$

This is the Microsoft Word portion of the application described in this question. It is considerably simpler than the excel portion of the project. Any classes not defined in this question can be found in the excel question. The full source code for this project including the UI can be found in my GitHub repository.

This portion simply generates a word document and then can save it to a file or print it.

CWordInteropMethods.cs

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using Word = Microsoft.Office.Interop.Word;

namespace RentRosterAutomation
{
    // Each building in the complex contains 3 floors of apartments. The documnets
    // generated by Microsoft Word have 3 columns of data, one for each floor.
    // Prints and or saves a Microsoft Word Document for each building.
    class CWordInteropMethods
    {
        private string defaultSaveFolder;
        private object oMissing = Missing.Value;
        private object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

        public CWordInteropMethods(CUserPreferences inPreferences)
        {
            defaultSaveFolder = inPreferences.DefaultSaveDirectory;
        }

        public bool CreateMailistPrintAndOrSave(string documentName, CMailboxListData mailboxdata,
                bool addDateToDocName, bool addDateToTitle, bool save, bool print
            )
        {
            bool docGenerated = true;
            if (string.IsNullOrEmpty(documentName))
            {
                return false;
            }

            string fullFilePathName = FullFilePath(documentName, addDateToDocName);

            Word.Application wordApp = new Word.Application();

            try
            {
                Word.Document wordDoc = new Word.Document();
                wordApp.Visible = false;
                wordDoc = wordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                FormatDocMargins(ref wordDoc, wordApp);
                AddTitleToMailBoxList(ref wordDoc, mailboxdata.AddressStreetNumber, addDateToTitle);
                AddTenantTableToMailBoxList(ref wordDoc, mailboxdata, wordApp);

                object DoNotSaveChanges = PrintAndOrSave(wordDoc, save, print, fullFilePathName);
                wordDoc.Close(ref DoNotSaveChanges, ref oMissing, ref oMissing);
            }
            catch (Exception e)
            {
                string eMsg = "An error occurred while generating the Word Document for "
                    + documentName + " : " + e.Message;
                docGenerated = false;
                MessageBox.Show(eMsg);
            }
            wordApp.Quit();

            return docGenerated;
        }

        private object PrintAndOrSave(Word.Document wordDoc, bool save, bool print, string fullFilePathName)
        {
            object DoNotSaveChanges = oMissing;
            if (print)
            {
                wordDoc.PrintOut();
            }
            if (save)
            {
                SaveFile(wordDoc, fullFilePathName);
            }
            else
            {
                DoNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
            }
            return DoNotSaveChanges;
        }

        private void AddTitleToMailBoxList(ref Word.Document wordDoc, int addressNumber, bool addDateToTitle)
        {
            object oMissing = Missing.Value;

            Word.Paragraph MailboxListTitle = wordDoc.Content.Paragraphs.Add(ref oMissing);
            MailboxListTitle.Range.Text = addressNumber.ToString();
            MailboxListTitle.Range.Font.Size = 78;
            MailboxListTitle.Range.Font.Bold = 1;
            MailboxListTitle.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            MailboxListTitle.SpaceAfter = 0;
            MailboxListTitle.Range.InsertParagraphAfter();
            if (addDateToTitle)
            {
                DateTime todaysDate = DateTime.Today;
                Word.Paragraph todaysDatePara = wordDoc.Content.Paragraphs.Add(ref oMissing);
                todaysDatePara.Range.Text = todaysDate.ToString("MM/dd/yyyy");
                todaysDatePara.Range.Font.Size = 7;
                todaysDatePara.Range.Bold = 0;
                todaysDatePara.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                todaysDatePara.SpaceAfter = 5;
                todaysDatePara.Range.InsertParagraphAfter();
            }
        }

        // Table is 2 columns for first and second floors, 1 column
        // merged for third floor
        private void AddTenantTableToMailBoxList(ref Word.Document wordDoc,
            CMailboxListData mailboxData, Word.Application wordApp)
        {
            object oMissing = Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            int rowCount = (mailboxData.FirstFloor.Count > mailboxData.SecondFloor.Count) ?
                mailboxData.FirstFloor.Count : mailboxData.SecondFloor.Count;
            int maxDoubleColumn = rowCount;
            rowCount += mailboxData.ThirdFloor.Count;
            rowCount += 1; // One empty row between third floor column and upper colums

            Word.Table tenantTable = CreateAndFormatTenatTable(rowCount, maxDoubleColumn,
                wordDoc, wordApp);

            FillFloor1Stand2Nd(mailboxData, maxDoubleColumn, ref tenantTable);
            FillThirdFloor(mailboxData, maxDoubleColumn, wordApp, ref tenantTable);
        }

        private void FillThirdFloor(CMailboxListData mailboxData, int maxDoubleColumn, Word.Application wordApp, ref Word.Table tenantTable)
        {
            int row = maxDoubleColumn + 2;
            List<CApartment> ThirdFloor = mailboxData.ThirdFloor;
            for (int i = 0; i < ThirdFloor.Count; i++)
            {
                Word.Cell currentCell = tenantTable.Cell(row, 1);
                tenantTable.Rows[row].Cells[1].Merge(tenantTable.Rows[row].Cells[2]);
                currentCell.LeftPadding = wordApp.InchesToPoints((float)2.5);
                AssignCellValueAndFormat(ref currentCell, MailBoxListEntry(ThirdFloor, i));
                row++;
            }
        }

        private void FillFloor1Stand2Nd(CMailboxListData mailboxData, int maxDoubleColumn, ref Word.Table tenantTable)
        {
            List<CApartment> FirstFloor = mailboxData.FirstFloor;
            List<CApartment> SecondFloor = mailboxData.SecondFloor;

            int firstFloorCount = FirstFloor.Count;
            int secondFloorCount = SecondFloor.Count;

            int row = 1;
            for (; row <= maxDoubleColumn; row++)
            {
                if (row <= firstFloorCount)
                {
                    Word.Cell currentCell = tenantTable.Cell(row, 1);
                    AssignCellValueAndFormat(ref currentCell, MailBoxListEntry(FirstFloor, row - 1));
                }
                if (row <= secondFloorCount)
                {
                    Word.Cell currentCell = tenantTable.Cell(row, 2);
                    AssignCellValueAndFormat(ref currentCell, MailBoxListEntry(SecondFloor, row - 1));
                }
            }

        }

        private Word.Table CreateAndFormatTenatTable(int rowCount, int maxDoubleColumn,
            Word.Document wordDoc, Word.Application wordApp)
        {
            Word.Table tenantTable;
            Word.Range wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            tenantTable = wordDoc.Tables.Add(wrdRng, rowCount, 2, ref oMissing, ref oMissing);
            tenantTable.Range.Font.Size = (maxDoubleColumn < 14) ? 18 : 16;
            tenantTable.Range.Font.Bold = 1;
            tenantTable.Range.Font.Name = "Arial";
            tenantTable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowLeft;
            tenantTable.Columns.SetWidth(wordApp.InchesToPoints((float)3.25), Word.WdRulerStyle.wdAdjustSameWidth);

            return tenantTable;
        }

        private void AssignCellValueAndFormat(ref Word.Cell currentCell, string cellValue)
        {
            currentCell.Range.Text = cellValue;
            currentCell.WordWrap = true;
            currentCell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
        }

        private string MailBoxListEntry(List<CApartment> apartments, int row)
        {
            string mbListEntry = apartments[row].ApartmentNumber.ToString();
            mbListEntry += "  " + apartments[row].renter.MailboxListOccupantEntry();

            return mbListEntry;
        }

        private string FullFilePath(string documentName, bool addDateToFileName)
        {
            string fileToSave = defaultSaveFolder + "\\" + documentName;

            if (addDateToFileName)
            {
                DateTime todaysDate = DateTime.Today;
                string dtNoSlash = todaysDate.ToString("MMddyyyy");
                fileToSave += "_" + dtNoSlash;
            }
            fileToSave += ".docx";

            return fileToSave;
        }

        private void SaveFile(Word.Document wordDoc, string documentName)
        {
            if (!string.IsNullOrEmpty(defaultSaveFolder))
            {
                object oMissing = Missing.Value;
                object newfile = documentName;
                wordDoc.SaveAs(ref newfile, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing);
            }
            else
            {
                wordDoc.Save();
            }
        }

        private void FormatDocMargins(ref Word.Document wordDoc, Word.Application wordApp)
        {
            wordDoc.PageSetup.TopMargin = wordApp.InchesToPoints((float)0.375);
            wordDoc.PageSetup.LeftMargin = wordApp.InchesToPoints((float)1);
            wordDoc.PageSetup.RightMargin = wordApp.InchesToPoints((float)1);
            wordDoc.PageSetup.BottomMargin = wordApp.InchesToPoints((float)0.375);
        }
    }
}

CUserPreferences.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;


namespace RentRosterAutomation
{

    // Reads and writes the user preferences file.
    public class CUserPreferences
    {
        private CPrintSavePreference.PrintSave printSaveValue;
        private CPrintSavePreference printSavePreference;
        private Dictionary<int, string> FieldNameByIndex;
        private Dictionary<string, int> IndexFromFieldName;
        private const int fileVersion = 1;
        private bool preferenceFileExists = false;
        private bool preferenceFileRead = false;

        public bool HavePreferenceData { get { return preferenceFileRead; } }
        public CPrintSavePreference.PrintSave PrintSaveOptions { get { return printSaveValue; } set { printSaveValue = value; } }
        public string RentRosterFile { get; set; }
        public string RentRosterSheet { get; set; }
        public string DefaultSaveDirectory { get; set; }

        public CUserPreferences()
        {
            printSavePreference = new CPrintSavePreference();
            InitDictionaries();
            SetValuesToUndefinedState();
        }

        public CUserPreferences(string PreferencesFileName)
        {
            printSavePreference = new CPrintSavePreference();
            InitDictionaries();
            preferenceFileExists = File.Exists(PreferencesFileName);
            if (preferenceFileExists)
            {
                preferenceFileRead = ReadPreferenceFile(PreferencesFileName);
            }
            else
            {
                SetValuesToUndefinedState();
            }

        }

        public bool SavePreferencesToFile(string preferencesFileName)
        {
            StreamWriter rentRosterPreferencesfile = new StreamWriter(preferencesFileName);
            try
            {
                WritePreferencesToDisc(rentRosterPreferencesfile);
                rentRosterPreferencesfile.Flush();
                rentRosterPreferencesfile.Close();

                preferenceFileExists = true;
                preferenceFileRead = true;

                return true;
            }
            catch (IOException)
            {
                MessageBox.Show("Unable to write to preferences file: " + preferencesFileName);
                return false;
            }
        }

        private void InitDictionaries()
        {

            FieldNameByIndex = new Dictionary<int, string>();
            int fieldNameCount = fileValueIds.Length;
            for (int i = 0; i < fieldNameCount; ++i)
            {
                FieldNameByIndex.Add(i, fileValueIds[i]);
            }

            IndexFromFieldName = new Dictionary<string, int>();
            for (int i = 0; i < fieldNameCount; ++i)
            {
                IndexFromFieldName.Add(fileValueIds[i], i);
            }

        }

        private void SetValuesToUndefinedState()
        {
            PrintSaveOptions = CPrintSavePreference.PrintSave.PrintOnly;
        }

        // These constants and variables are used when reading and writing
        // the preferences to and from the preference file.
        private const int fileVersionId = 0;
        private const int printSaveOptionId = 1;
        private const int defaultSaveDirId = 2;
        private const int rentRosterFileId = 3;
        private const int rentRosterSheetNameId = 4;
        private string[] fileValueIds =
        {
            "FileVersion:",
            "PrintSaveValue:",
            "DefaultSaveDirectory:",
            "RentRosterFile:",
            "RentRosterSheet:"
        };

        private void WritePreferencesToDisc(StreamWriter preferenceFile)
        {
            preferenceFile.WriteLine(fileValueIds[fileVersionId] + " " + fileVersion.ToString());
            preferenceFile.WriteLine(fileValueIds[printSaveOptionId] + " " +
                printSavePreference.ConvertPrintSaveToString(printSaveValue));
            preferenceFile.WriteLine(fileValueIds[defaultSaveDirId] + " " + DefaultSaveDirectory);
            preferenceFile.WriteLine(fileValueIds[rentRosterFileId] + " " + RentRosterFile);
            preferenceFile.WriteLine(fileValueIds[rentRosterSheetNameId] + " " + RentRosterSheet);

        }

        private void ConvertandTestFileVersion(string fileInput)
        {
            try
            {
                int testFileVersion = Int32.Parse(fileInput);
                if (testFileVersion != fileVersion)
                {
                    if (testFileVersion < fileVersion)
                    {
                        MessageBox.Show("Preference file version " + fileInput + " out of date, please edit preferences to add new field values.");
                    }
                    else
                    {
                        MessageBox.Show("This version of the Tenant Roster tool does not support all the features of the tool that generated the file.");
                    }
                }
            }
            catch (FormatException e)
            {
                string eMsg = "Reading preferences File Version failed: " + e.Message;
                MessageBox.Show(eMsg);
            }
        }

        private bool ReadPreferenceFile(string fileName)
        {
            bool fileReadSucceeded = true;
            string[] lines;

            if (File.Exists(fileName))
            {
                try
                {
                    lines = File.ReadAllLines(fileName);
                    fileReadSucceeded = GetPreferenceValues(lines);
                }
                catch (IOException)
                {
                    fileReadSucceeded = false;
                }
            }

            return fileReadSucceeded;
        }

        private bool GetPreferenceValues(string[] lines)
        {
            bool hasAllFields = false;
            int requiredFieldCount = 0;
            int lineCount = lines.Length;
            for (int i = 0; i < lineCount; ++i)
            {
                string[] nameAndValue = lines[i].Split(' ');
                int fieldIndex;
                IndexFromFieldName.TryGetValue(nameAndValue[0], out fieldIndex);
                switch (fieldIndex)
                {
                    case fileVersionId:
                        ConvertandTestFileVersion(nameAndValue[1]);
                        requiredFieldCount++;
                        break;

                    case printSaveOptionId:
                        printSaveValue = printSavePreference.ConvertStringToPrintSave(nameAndValue[1]);
                        requiredFieldCount++;
                        break;

                    case defaultSaveDirId:
                        DefaultSaveDirectory = CorrectForMuliWordNames(nameAndValue);
                        requiredFieldCount++;
                        break;

                    case rentRosterFileId:
                        RentRosterFile = CorrectForMuliWordNames(nameAndValue);
                        requiredFieldCount++;
                        break;

                    case rentRosterSheetNameId:
                        RentRosterSheet = CorrectForMuliWordNames(nameAndValue);
                        requiredFieldCount++;
                        break;

                    default:
                        MessageBox.Show("Reading preference file: Unknown field identity");
                        return false;
                }
            }

            if (requiredFieldCount == fileValueIds.Length)
            {
                hasAllFields = true;
            }

            return hasAllFields;
        }

        private string CorrectForMuliWordNames(string[] lineValues)
        {
            string wholeName = lineValues[1];
            for (int i = 2; i < lineValues.Length; i++)
            {
                wholeName += " " + lineValues[i];
            }

            return wholeName;
        }

    }
}

CPrintSavePreference.cs

using System.Collections.Generic;

namespace RentRosterAutomation
{
    public class CPrintSavePreference
    {
        private Dictionary<PrintSave, string> PrintSaveToStringDic;
        private Dictionary<string, PrintSave> StringToPrintSaveDic;

        public enum PrintSave
        {
            PrintOnly,
            PrintAndSave,
            SaveOnly
        }

        public CPrintSavePreference()
        {
            InitDictionaries();
        }

        public string ConvertPrintSaveToString(PrintSave printSave)
        {
            string printSaveString;

            PrintSaveToStringDic.TryGetValue(printSave, out printSaveString);

            return printSaveString;
        }

        public PrintSave ConvertStringToPrintSave(string printSaveString)
        {
            PrintSave retValue;

            StringToPrintSaveDic.TryGetValue(printSaveString, out retValue);

            return retValue;
        }

        private void InitDictionaries()
        {
            PrintSaveToStringDic = new Dictionary<PrintSave, string>();
            PrintSaveToStringDic.Add(PrintSave.PrintOnly, "Print_Only");
            PrintSaveToStringDic.Add(PrintSave.PrintAndSave, "Print_and_Save");
            PrintSaveToStringDic.Add(PrintSave.SaveOnly, "Save_Only");

            StringToPrintSaveDic = new Dictionary<string, PrintSave>();
            StringToPrintSaveDic.Add("Print_Only", PrintSave.PrintOnly);
            StringToPrintSaveDic.Add("Print_and_Save", PrintSave.PrintAndSave);
            StringToPrintSaveDic.Add("Save_Only", PrintSave.SaveOnly);
        }

    }
}

Form_PrintMailboxLists .cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace RentRosterAutomation
{
    public partial class Form_PrintMailboxLists : Form
    {
        private readonly CUserPreferences preferences;
        private CPrintSavePreference.PrintSave printSave;
        private bool addDateToFileName = false;
        private bool addDateToTitle = false;
        private string selectedBuildings;
        private CPropertyComplex propertyComplex;
        private CWordInteropMethods wordInteropMethods;

        public Form_PrintMailboxLists()
        {
            InitializeComponent();
            preferences = Program.preferences;
            propertyComplex = Program.excelInteropMethods.Complex;
            wordInteropMethods = new CWordInteropMethods(preferences);
        }

        private void PrintMailboxLists_Form_Load(object sender, EventArgs e)
        {
            List<string> buildings = propertyComplex.BuildingAddressList;

            foreach (string building in buildings)
            {
                SelectBuilding2Print_listBox.Items.Add(building);
            }
            SelectBuilding2Print_listBox.Items.Add("All Buildings");

            if (preferences.HavePreferenceData)
            {
                printSave = preferences.PrintSaveOptions;
                PrintSaveChange();
            }

            AddDateToFileName_CB.Checked = addDateToFileName;
            AddDateUnderAddress_CB.Checked = addDateToTitle;
            PML_SaveAndPrint_Button.Enabled = false;
        }

        private void AddDateToFileName_CB_CheckedChanged(object sender, EventArgs e)
        {
            addDateToFileName = !addDateToFileName;
        }

        private void AddDateUnderAddress_CB_CheckedChanged(object sender, EventArgs e)
        {
            addDateToTitle = !addDateToTitle;
        }

        private void PML_SaveAndPrint_Button_Click(object sender, EventArgs e)
        {
            if (String.Compare(selectedBuildings, "All Buildings") == 0)
            {
                List<int> StreetNumbers = propertyComplex.StreetNumbers;

                foreach (int streetNumber in StreetNumbers)
                {
                    printAndOrSaveMailList(streetNumber);
                }
            }
            else
            {
                string streetAddress = selectedBuildings.Substring(0, 5);
                printAndOrSaveMailList(streetAddress);
            }

            Close();
        }

        private void printAndOrSaveMailList(string streetAddress)
        {
            int iStreetNumber = 0;
            if (Int32.TryParse(streetAddress, out iStreetNumber))
            {
                printAndOrSaveMailList(iStreetNumber);
            }
            else
            {
                MessageBox.Show("Non Numeric string passed into PrintMailboxLists_Form::printAndOrSaveMailList().");
            }
        }

        private void PML_PrintOnly_RB_CheckedChanged(object sender, EventArgs e)
        {
            printSave = CPrintSavePreference.PrintSave.PrintOnly;
        }

        private void PML_SavelOnly_RB_CheckedChanged(object sender, EventArgs e)
        {
            printSave = CPrintSavePreference.PrintSave.SaveOnly;
        }

        private void PML_PrintAndSave_RB_CheckedChanged(object sender, EventArgs e)
        {
            printSave = CPrintSavePreference.PrintSave.PrintAndSave;
        }

        private void PrintSaveChange()
        {
            switch (printSave)
            {
                case CPrintSavePreference.PrintSave.PrintAndSave:
                    PML_PrintAndSave_RB.Checked = true;
                    break;

                case CPrintSavePreference.PrintSave.SaveOnly:
                    PML_SavelOnly_RB.Checked = true;
                    break;

                default:
                    PML_PrintOnly_RB.Checked = true;
                    break;
            }
        }

        private void SelectBuilding2Print_listBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SelectBuilding2Print_listBox.SelectedItem != null)
            {
                selectedBuildings = SelectBuilding2Print_listBox.SelectedItem.ToString();
                PML_SaveAndPrint_Button.Enabled = true;
            }
        }

        private void printAndOrSaveMailList(int streetAddress)
        {
            bool save = ((printSave == CPrintSavePreference.PrintSave.PrintAndSave) ? true :
                (printSave == CPrintSavePreference.PrintSave.SaveOnly) ? true : false);
            bool print = ((printSave == CPrintSavePreference.PrintSave.PrintAndSave) ? true :
                (printSave == CPrintSavePreference.PrintSave.PrintOnly) ? true : false);

            string documentName = "MailboxList_" + streetAddress;

            string statusMessage = (print && save) ? "Printing and Saving " :
                (print) ? "Printing " : "Saving ";
            statusMessage += "the mailbox list for " + streetAddress;

            Form_CurrentProgressStatus psStatus = new Form_CurrentProgressStatus();
            psStatus.MessageText = statusMessage;
            psStatus.Show();

            CBuilding building = propertyComplex.GetBuilding(streetAddress);
            if (building != null)
            {
                CMailboxListData mailboxList = Program.excelInteropMethods.GetMailboxData(building);
                if (mailboxList != null)
                {
                    wordInteropMethods.CreateMailistPrintAndOrSave(documentName,
                        mailboxList, addDateToFileName, addDateToTitle, save, print);
                }
            }

            psStatus.Close();
        }

    }
}
\$\endgroup\$
2
\$\begingroup\$

Error Handling
Similar to the Excel part, an exception in the writing can cause an orphaned Word instance. Placing the Quit() in a finally block will help that

try
{
    var wordDoc = wordApp.Documents.Add();

    FormatDocMargins(ref wordDoc, wordApp);
    AddTitleToMailBoxList(wordDoc, mailboxdata.AddressStreetNumber, addDateToTitle);
    AddTenantTableToMailBoxList(wordDoc, mailboxdata, wordApp);

    object DoNotSaveChanges = PrintAndOrSave(wordDoc, save, print, fullFilePathName);
    wordDoc.Close(ref DoNotSaveChanges);
}
catch (Exception e)
{
    string eMsg = "An error occurred while generating the Word Document for "
        + documentName + " : " + e.Message;
    docGenerated = false;
    MessageBox.Show(eMsg);
}
finally
{
    wordApp.Quit();
}

NOTE:
Most of the Missing parameters are optional and can be omitted.
It is not necessary to use reference parameters when passing the document around. The only time that we would need the parameter to be ref is if we were creating the document in the method and wanted to return it in the parameter.

In the original code we create the document instance twice

Word.Document wordDoc = new Word.Document();
wordApp.Visible = false;
wordDoc = wordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

only the second is needed (with the optional missing params omitted)

Word.Document wordDoc = wordApp.Documents.Add();

Other
Under what conditions can the documentName be null or empty? This strikes me as a condition that should be handled long before we get to this method.

It is possible to not print or save (pass in false for each) and still have docGenerated be true. Is this intended?

As far as I can see the CUserPreferences and CPrintSavePreference are not used (we read the defaultSaveFolder from CUserPreferences in the ctor but that is it). Am I missing something?

It depends upon the full requirements but for some quick print/save preferences a Flags enum is useful

[Flags]
internal enum WriterTargets
{
    None = 0,
    Print = 1,
    Save = 2
}

We can set them and parse them using the built in functionality

var targets = WriterTargets.Print;
Console.WriteLine(targets.ToString());

gives 'Print'

targets =  WriterTargets.Save;
Console.WriteLine(targets.ToString());

gives 'Save'

targets = WriterTargets.Save | WriterTargets.Print;
Console.WriteLine(targets.ToString());

or

targets = (WriterTargets)Enum.Parse(typeof(WriterTargets), "Save, Print");
Console.WriteLine(targets.ToString());

gives 'Print, Save'

\$\endgroup\$
2
  • \$\begingroup\$ About Print and Save, there is already an enum, one of the two will always be true, it is handled in the UI side of things, see the CPrintSavePreference.cs class. \$\endgroup\$
    – pacmaninbw
    Jan 5 at 15:20
  • \$\begingroup\$ I've added the Form that calls the Word Interop class. In the current usage documentName can't be null, but I've worked on large projects where others had to alter the code and I'm careful. \$\endgroup\$
    – pacmaninbw
    Jan 5 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.