遍历目录并追加到文件

时间:2018-10-01 10:30:15

标签: c# ms-word directory office-interop

我试图选择一个路径,然后我想读取目录。在每个目录中都有多个Word文件,我想打开每个Word文件,复制其内容并将其粘贴到新的Word文档中。

例如,如果我的目录中有6个Word文件,我想打开一个新的Word文档,然后打开目录中的第一个文档,复制其内容并将其粘贴到新文档中,然后循环直到读取所有文档

到目前为止,我已经可以遍历docs了,但是新创建的word文件仅获取最后打开的文档。下面是我的代码。

namespace combiner
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // For optional parameters create a missing object    
            object missing = System.Reflection.Missing.Value;

            // Create an object of application class    
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();

            // add a document in the Application
            Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            // declare variables for setting the position within the document    
            object start = 0;    
            object end = 0;

            // create a range object which starts at 0    
            Range rng = adoc.Range(ref start, ref missing);       

            string path = @"C:\demo";    

            string[] files = Directory.GetDirectories(path);

            for (int i = 0; i < files.Length; i++)
            {
                string[] ora = Directory.GetFiles(files[i], "*.docx", SearchOption.AllDirectories);

                foreach (string f in ora)
                {
                    MessageBox.Show(f);
                    textBox1.Text = f.ToString();

                    // insert a file
                    rng.InsertFile(textBox1.Text, ref missing, ref missing, ref missing, ref missing);

                    // now make start to point to the end of the content of the first document
                    start = WordApp.ActiveDocument.Content.End - 1;

                    // create another range object with the new value for start
                    Range rng1 = adoc.Range(ref start, ref missing);

                    // insert the another document
                   rng1.InsertFile(textBox1.Text, ref missing, ref missing, ref missing, ref missing);

                    // now make start to point to the end of the content of the first document
                    start = WordApp.ActiveDocument.Content.End - 1;
                }

                // make the word appliction visible

                WordApp.Visible = true;
                adoc.SaveAs2(@"D:\fulltest.docx");
            }
        }
    }
}

0 个答案:

没有答案