Stack Exchange
Use Word Interop to open file Word and replace some text in SharePoint 2010
I try to use: Microsoft.Office.Interop.Word to open a Word file.
This is my code in funcs LoadFile:
using Word = Microsoft.Office.Interop.Word;
private void LoadFile( string MyID )
    {
        Word.Application word = new Word.Application();
        Word.Document doc = new Word.Document();
        object missing = System.Type.Missing;

        try
        {
            object fileName = "File URL";
            doc = word.Documents.Open(ref fileName,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);
            doc.Activate();
            // Replace [$ID] by MyID
            foreach (Word.Range tmpRange in doc.StoryRanges)
            {
                tmpRange.Find.Text = "[$ID]";
                tmpRange.Find.Replacement.Text = MyID;
                tmpRange.Find.Wrap = Word.WdFindWrap.wdFindContinue;
                object replaceAll = Word.WdReplace.wdReplaceAll;
                tmpRange.Find.Execute(ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref replaceAll,
                    ref missing, ref missing, ref missing, ref missing);
            }

            // And open this file after replace
            word.Visible = true;
        }
        catch (Exception ex)
        {
            doc.Close(ref missing, ref missing, ref missing);
            word.Application.Quit(ref missing, ref missing, ref missing);
        }
    }

In ASP.NET, this file is open and replace [$ID] by MyID. But I can't use this code in a Webpart in SharePoint 2010. It's error.
Do anyone give me some advice or can I achieve this goal by another way?
My goal is: file doc opened by MS Word and it replaced some texts.

Office Interop is NOT supported by MS in "server-like scenarios" (which IIS/ASP.NET/Sharepoint is a special kind of) - see http://support.microsoft.com/default.aspx?scid=kb;EN-US;q257757#kb2
Your options include several libtraries (free and commercial) - for example:

MS OpenXML SDK (free)
Aspose.Words (commercial)

