Copy text from word file to a new word
.net, .net-4.0, c#, ms-word, office-interop
Solution
All you need to do is this:
using System.Runtime.InteropServices;
using MSWord = Microsoft.Office.Interop.Word;
namespace ConsoleApplication6
{
class Program
{
static void Main()
{
var application = new MSWord.Application();
var originalDocument = application.Documents.Open(@"C:\whatever.docx");
originalDocument.ActiveWindow.Selection.WholeStory();
var originalText = originalDocument.ActiveWindow.Selection;
var newDocument = new MSWord.Document();
newDocument.Range().Text = originalText.Text;
newDocument.SaveAs(@"C:\whateverelse.docx");
originalDocument.Close(false);
newDocument.Close();
application.Quit();
Marshal.ReleaseComObject(application);
}
}
}
Problem
I am reading the text from word file and replace some text from the readed text. ``` var wordApp = new Microsoft.Office.Interop.Word.Application(); object file = path; object nullobj = System.Reflection.Missing.Value; var doc = wordApp.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); doc.ActiveWindow.Selection.WholeStory(); doc.ActiveWindow.Selection.Copy(); IDataObject data = Clipboard.GetDataObject(); var text =data.GetData(DataFormats.Text); ``` So I have text from original word file, and now I need it to pass to a new word file which not exist (New Text). I tried ``` ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "WINWORD.EXE"; Process.Start(startInfo); ``` This opens new word file which not saved physically in file system which is fine. But I am not sure how can pass the text value to this new file. Update After running above code I tried ``` var wordApp = new Microsoft.Office.Interop.Word.Application(); var doc = wordApp.ActiveDocument; ``` Which comes up with "This command is not available because no document is open."