I already can join two or more word documents from their file path.
How can i join them without saving them to disk?
string TemporaryPath = "";
string TemplatePath = "";
Object MissingValue;
object OFalse = false;
object OTrue = true;
public WordWorker()
{
TemporaryPath = AppDomain.CurrentDomain.BaseDirectory + "Temporary";
MissingValue = Missing.Value;
TemplatePath = @"C:\TemplateTest.dotx";
}
public void Merge()
{
object wdPageBreak = 7;
object wdStory = 6;
Application WordApplication = new Application();
Document WordDocument = WordApplication.Documents.Add(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);
for (int i = 0; i < 100; i++)
{
string Path = CreateWordFromTemplate(WordApplication, TemplatePath, new Dictionary<string, string>() { { "Name", "MyNewValue" + i } });
WordDocument.Application.Selection.Range.InsertFile(Path, ref MissingValue, ref MissingValue, ref MissingValue, ref OFalse);
}
object WordSaveFormat = WdSaveFormat.wdFormatDocument;
object MergedDocumentPath = TemporaryPath + "Merged.dox";
WordDocument.SaveAs(ref MergedDocumentPath, ref WordSaveFormat, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);
WordApplication.Application.Quit();
}
public string CreateWordFromTemplate(Application WordApplication, Object oTemplatePath, Dictionary<string, string> dictionary)
{
Guid DocumentID = Guid.NewGuid();
Document WordDocument = new Document();
WordDocument = WordApplication.Documents.Add(ref oTemplatePath, ref MissingValue, ref MissingValue, ref MissingValue);
foreach (Field FieldToMerge in WordDocument.Fields)
{
Range FieldRange = FieldToMerge.Code;
String FieldText = FieldRange.Text;
if (FieldText.StartsWith(" MERGEFIELD"))
{
Int32 EndMerge = FieldText.IndexOf("\\");
Int32 FieldNameLength = FieldText.Length - EndMerge;
String FieldName = FieldText.Substring(11, EndMerge - 11).Trim();
if (dictionary.ContainsKey(FieldName))
{
FieldToMerge.Select();
WordApplication.Selection.TypeText(dictionary[FieldName]);
}
}
}
string Path = @"{0}\{1}.doc".SFormat(TemporaryPath, DocumentID);
WordDocument.SaveAs(Path);
WordDocument.Close();
return Path;
}