4

I have this code:

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
object nullobj = System.Reflection.Missing.Value;
object file = openFileDialog1.FileName;
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(
  ref file, ref nullobj, ref nullobj,
  ref nullobj, ref nullobj, ref nullobj,
  ref nullobj, ref nullobj, ref nullobj,
  ref nullobj, ref nullobj, ref nullobj,
  ref nullobj, ref nullobj, ref nullobj);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
string text = data.GetData(DataFormats.Text).ToString();
textBox2.Text = text;
doc.Close(ref nullobj, ref nullobj, ref nullobj);
app.Quit(ref nullobj, ref nullobj, ref nullobj);

But it does not return a page number. How can I get the page number?

KatieK
  • 13,586
  • 17
  • 76
  • 90
monkey_boys
  • 7,108
  • 22
  • 58
  • 82

3 Answers3

6

I'd say this is a better solution

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
object nullobj = System.Reflection.Missing.Value;
object file = openFileDialog1.FileName;
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(
  ref file, ref nullobj, ref nullobj,
  ref nullobj, ref nullobj, ref nullobj,
  ref nullobj, ref nullobj, ref nullobj,
  ref nullobj, ref nullobj, ref nullobj,
  ref nullobj, ref nullobj, ref nullobj);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();

// get number of pages
Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
int pages = doc.ComputeStatistics(stat, Type.Missing);

string text = data.GetData(DataFormats.Text).ToString();
textBox2.Text = text;
doc.Close(ref nullobj, ref nullobj, ref nullobj);
app.Quit(ref nullobj, ref nullobj, ref nullobj);
Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
2

Look at this example:

http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx

Specifically, look at Word.WdFieldType.wdFieldPage and Word.WdFieldType.wdFieldNumPages.

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
  • 1
    This would be a better answer if it included the essential parts of the answer here, and provided the link for reference. Link-only answers can become invalid if the linked page changes. – KatieK Dec 18 '12 at 00:16
0

For me, the ComputeStatistics function would give me a higher number than the actual number of pages so that didn't work for me.

I used range.get_Information()

var range = doc.Range().GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToLast);
var numPages = range.get_Information(WdInformation.wdActiveEndPageNumber);

The first line gets the range on the last page of the document. The second line gets the page where the range is.

zeta
  • 1,517
  • 1
  • 20
  • 14