12 Replies - 576 Views - Last Post: 20 February 2013 - 08:53 PM Rate Topic: -----

#1 varunit  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 39
  • Joined: 03-September 09

Moving cursor to beginning of document - C# and Word Interop

Posted 13 February 2013 - 10:22 AM

As the title suggest, I'm trying to create word document through C#. I'm able to create new document, but I also want to open an existing document and add the content to it from the beginning. That is I want the new content to appear at the top. Below is what I've done so far, but always the content gets appended at the end.

using System.IO;
using Word = Microsoft.Office.Interop.Word;
namespace Snapper
{
    class WordDocumentGenerator
    {
        public void CreateWordDocument(string fileName)
        {
            string originalPath = Directory.GetCurrentDirectory();
            string path = originalPath;
            path += @"\snapshots";
            object oMissing = System.Reflection.Missing.Value;
            
            //Create a new Word Application
            Word._Application wordApp = new Word.Application();
            wordApp.Visible = false;
            try
            {
                //Create a new blank document
                object filePath = originalPath + @"\documents" + @"\TSC1.doc";
                Word._Document doc = wordApp.Documents.Open(ref filePath,
                                                            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);
                string[] images = Directory.GetFiles(path);

                //Create a range

                object what = Word.WdGoToItem.wdGoToLine;
                object which = Word.WdGoToDirection.wdGoToFirst;
                object myTrue = true;
                object myFalse = false;
                doc.GoTo(ref what, ref which, ref oMissing, ref oMissing);
                
                //Insert filename as header
                var pText = doc.Paragraphs.Add(ref oMissing);
                pText.Format.SpaceAfter = 10f;
                pText.Range.Text = fileName;
                pText.Range.InsertParagraphAfter();

                foreach (var image in images)
                {                  
                    var pImage = doc.Paragraphs.Add(ref oMissing);
                    pImage.Format.SpaceAfter = 10f;
                    object myRng = pImage.Range;
                    doc.InlineShapes.AddPicture(image, ref myFalse, ref myTrue, ref myRng);
                }                
                path = originalPath;
                path += @"\documents";

                DirectoryInfo docDir = new DirectoryInfo(path);
                if (!docDir.Exists)
                {
                    docDir.Create();
                }

                object savePath = path + @"\" + fileName + ".doc";

                doc.SaveAs(ref savePath,
                    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
                   );
                doc.Save();
            }            
            finally
            {
                wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
            }                                                                          
        }
        
    }
}




I've tried doc.GoTo() method, but still no luck.
Could anyone help me in solving my problem. Thanks

EDIT: Forgot to mention that I've also tried using Range by specifying both start and end as 0.

This post has been edited by varunit: 13 February 2013 - 10:24 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Moving cursor to beginning of document - C# and Word Interop

#2 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3331
  • View blog
  • Posts: 11,261
  • Joined: 12-December 12

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 13 February 2013 - 11:03 AM

Having opened the document..

 wordApp.Selection.HomeKey(Unit: WdUnits.wdStory);

This post has been edited by andrewsw: 13 February 2013 - 11:04 AM

Was This Post Helpful? 0
  • +
  • -

#3 varunit  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 39
  • Joined: 03-September 09

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 13 February 2013 - 08:23 PM

Thanks. will give it a shot and post the results
Was This Post Helpful? 0
  • +
  • -

#4 varunit  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 39
  • Joined: 03-September 09

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 13 February 2013 - 08:52 PM

I just tried what andrewsw has suggested, but still the content is placed at the end of document. The document which I want my new content to be inserted already contain a series of text and images.
I've also tried the combination of
object units = Word.WdUnits.Story;
wordApp.Selection.HomeKey(ref units, ref oMissing);
var pText = doc.Paragraphs.Add(ref oMissing);  
pText.Format.SpaceAfter = 10f;  
pText.Range.InsertParagraphAfter();  



Can someone help me in moving the cursor to beginning of document and insert my new content from there?
Was This Post Helpful? 0
  • +
  • -

#5 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,673
  • Joined: 24-August 11

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 14 February 2013 - 08:13 AM

This may be a little dirty, but you could read the contents out of the file and append them to the content you're adding, and overwrite the contents of the file with the result.
Was This Post Helpful? 0
  • +
  • -

#6 varunit  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 39
  • Joined: 03-September 09

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 14 February 2013 - 09:59 AM

@h4nnib4l. This is the worst case scenario. I'll have to go by this method if there is no choice left.
Was This Post Helpful? 0
  • +
  • -

#7 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3331
  • View blog
  • Posts: 11,261
  • Joined: 12-December 12

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 14 February 2013 - 10:33 AM

wordApp.Selection.HomeKey(6);


6 is the numerical value of the Word intrinsic constant wdStory. If this doesn't work then it means the document is not active within Word.

There are other ways to navigate to the top (using the Range object) but much the simplest way is to make sure the document is active.

This post has been edited by andrewsw: 14 February 2013 - 10:33 AM

Was This Post Helpful? 0
  • +
  • -

#8 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3331
  • View blog
  • Posts: 11,261
  • Joined: 12-December 12

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 14 February 2013 - 11:02 AM

object units = Word.WdUnits.Story;
wordApp.Selection.HomeKey(ref units, ref oMissing);
var pText = doc.Paragraphs.Add(ref oMissing);  
pText.Format.SpaceAfter = 10f;  
pText.Range.InsertParagraphAfter();  


The cursor might be going to the top of the document but you are then adding a paragraph to the document, which will probably add it at the end (of the document).

If you don't have Bookmarks that you can rely on to navigate, then it is easiest to use Selection. The following example is written in Word VBA so you'll need to adjust it slightly:

application.Selection.HomeKey wdstory
application.Selection.MoveDown wdParagraph, 1
application.Selection.TypeParagraph 
application.Selection.TypeParagraph 
application.Selection.MoveUp wdParagraph, 2
application.Selection.TypeText "Hi there Word"

It might seem a little cumbersome, but unless you have pre-defined Bookmarks that you can use to navigate to, it is easier to use Selection than Range.

It is possible to use Range:

    Dim rng As Range
    Dim rngPara As Range
    
    Set rng = Activedocument.Range
    Set rngPara = rng.Paragraphs(1).Range
    rngPara.Text = "Using Range"

but, although a more professional approach (perhaps) it requires a little more effort.

Hint: If you are working with a pre-existing document or template, manually define Word-Bookmarks within it so that you can modify the document/template at these precise locations.
Was This Post Helpful? 1
  • +
  • -

#9 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,673
  • Joined: 24-August 11

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 14 February 2013 - 02:29 PM

It was offered as a worst-case scenario. :)
Was This Post Helpful? 0
  • +
  • -

#10 varunit  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 39
  • Joined: 03-September 09

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 14 February 2013 - 08:34 PM

@andrewsw. Thanks for the hints and code snippets. I'm new to C# and Word Interop.

View Postandrewsw, on 14 February 2013 - 11:02 AM, said:

It is possible to use Range:

    Dim rng As Range
    Dim rngPara As Range
    
    Set rng = Activedocument.Range
    Set rngPara = rng.Paragraphs(1).Range
    rngPara.Text = "Using Range"


but, although a more professional approach (perhaps) it requires a little more effort.

Hint: If you are working with a pre-existing document or template, manually define Word-Bookmarks within it so that you can modify the document/template at these precise locations.


This makes more sense and will try this and post the results. BTW if the document is not active, how do I make it active after opening?
Was This Post Helpful? 0
  • +
  • -

#11 varunit  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 39
  • Joined: 03-September 09

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 19 February 2013 - 08:27 PM

@andrewsw,
I've used you approach as a starting point and I'm able to move the cursor to beginning of doucment.
I've created a range object and set its start and end refereces to 0 and 0. Now the content gets inserted to the beginning but there is a little problem in that insertion. The new content gets inserted upside down in the order of insertion. i.e. The first piece of content goes to the last and the second one goes previous to the last and so on until the last content becomes the first. What I haven't tried is using the praragraphs[1].range yet. Any help you can provide?

Thanks
Was This Post Helpful? 0
  • +
  • -

#12 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,673
  • Joined: 24-August 11

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 20 February 2013 - 09:26 AM

It sounds like you are executing the logic to move to the beginning of the document each time you insert a line. Are you looping to write the contents to the file?
Was This Post Helpful? 0
  • +
  • -

#13 varunit  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 39
  • Joined: 03-September 09

Re: Moving cursor to beginning of document - C# and Word Interop

Posted 20 February 2013 - 08:53 PM

@h4nnib4l.
Yes I'm looping through a List of strings which contains either text or path of the image. So my loop will decide what is the current iteration and will insert a paragraph
//Before going into this for loop, I want my cursor/insertion point to be positioned
//at the top/starting of document and then insert the content one below the another through
//following looping condtruct.

for (var i = 0; i < 10; i++)
            {
                // Insert text
                var pText = document.Paragraphs.Add();
                pText.Format.SpaceAfter = 10f;
                pText.Range.Text = String.Format("This is line #{0}", i);
                pText.Range.InsertParagraphAfter();

                
                // Insert picture
                var pPicture = document.Paragraphs.Add();
                pPicture.Format.SpaceAfter = 10f;
                document.InlineShapes.AddPicture(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "img_1.png"), Range: pPicture.Range);

            }



Much similar to the above code with little modifications like I'm looping through a List of strings..
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1