Hi dnnyobi,
Refer Below Code
Namespace
C#
using System.IO;
VB.Net
Imports System.IO
Code
C#
protected void OnMerge(object sender, EventArgs e)
{
string[] allRTFDocument = Directory.GetFiles(@"C:\\Files", "*.rtf");
Merge(allRTFDocument, @"C:\\Final.rtf", true);
}
public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
{
object missing = System.Type.Missing;
object pageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage;
object outputFile = outputFilename;
Microsoft.Office.Interop.Word._Application wordApplication = new Microsoft.Office.Interop.Word.Application();
try
{
Microsoft.Office.Interop.Word.Document wordDocument = wordApplication.Documents.Add(
ref missing
, ref missing
, ref missing
, ref missing);
Microsoft.Office.Interop.Word.Selection selection = wordApplication.Selection;
int documentCount = filesToMerge.Length;
int breakStop = 0;
foreach (string file in filesToMerge)
{
breakStop++;
selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing);
if (insertPageBreaks && breakStop != documentCount)
{
selection.InsertBreak(ref pageBreak);
}
}
wordDocument.SaveAs(
ref outputFile
, 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);
wordDocument = null;
}
catch (Exception ex)
{
throw ex;
}
finally
{
wordApplication.Quit(ref missing, ref missing, ref missing);
}
}
VB.Net
Protected Sub OnMerge(ByVal sender As Object, ByVal e As EventArgs)
Dim allRTFDocument As String() = Directory.GetFiles("C:\Files"), "*.rtf")
Merge(allRTFDocument, "C:\Final.rtf", True)
End Sub
Public Shared Sub Merge(ByVal filesToMerge As String(), ByVal outputFilename As String, ByVal insertPageBreaks As Boolean)
Dim missing As Object = System.Type.Missing
Dim pageBreak As Object = Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage
Dim outputFile As Object = outputFilename
Dim wordApplication As Microsoft.Office.Interop.Word._Application = New Microsoft.Office.Interop.Word.Application()
Try
Dim wordDocument As Microsoft.Office.Interop.Word.Document = wordApplication.Documents.Add(missing, missing, missing, missing)
Dim selection As Microsoft.Office.Interop.Word.Selection = wordApplication.Selection
Dim documentCount As Integer = filesToMerge.Length
Dim breakStop As Integer = 0
For Each file As String In filesToMerge
breakStop += 1
selection.InsertFile(file, missing, missing, missing, missing)
If insertPageBreaks AndAlso breakStop <> documentCount Then
selection.InsertBreak(pageBreak)
End If
Next
wordDocument.SaveAs(outputFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)
wordDocument = Nothing
Catch ex As Exception
Throw ex
Finally
wordApplication.Quit(missing, missing, missing)
End Try
End Sub
Input File
File 1
File 2
Output Megged File