c# copy from text file to word document

Viewed 1982

I want to copy data from text file to word file. I already have tried it with different alternatives like string array, StringBuilder and StreamReader using Interop which works good, but it takes too much time. It would really be thankful if anyone can suggest me with a better one. Been through many forms on the web, but couldn't find.

FYI: My text file contains more than 1,00,000 lines.

This is one of which I have tried:

string[] lines = File.ReadAllLines(path); //path is text file path
var doc = new MSWord.Document();

foreach (string lin in lines)
{
    doc.Content.Text += lin.ToString();
}

doc.Save();

Well, this works good but takes a lot of time and also sometimes throws an error like:

Unhandled Exception: System.Runtime.InteropServices.COMException: Word has encountered a problem.

2 Answers
    static void Main(string[] args)
    {
        Word.Application wordApp = new Word.Application();
        Word.Document wordDoc = wordApp.Documents.Add();
        Stopwatch sw = Stopwatch.StartNew();
        System.Console.WriteLine("Starting");
        string path = @"C:\";
        StringBuilder stringBuilder = new StringBuilder();
        using (FileStream fs = File.Open(path + "\\big.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (BufferedStream bs = new BufferedStream(fs))
        using (StreamReader sr = new StreamReader(bs))
        {
            wordDoc.Content.Text = sr.ReadToEnd();
            wordDoc.SaveAs("big.docx");
        }
        sw.Stop();
        System.Console.WriteLine($"Complete Time :{sw.ElapsedMilliseconds}");
        System.Console.ReadKey();
    }

Output :

Starting
Complete Time :5556

Or You can use Parallel :

    using (StreamReader sr = new StreamReader(bs))
    {
        Parallel.ForEach(sr.ReadToEnd(), i=>
        {
            stringBuilder.Append(i);
        });
        wordDoc.Content.Text = stringBuilder.ToString();
        wordDoc.SaveAs(path + "\\big3.docx");
    }

Output:

Starting
Complete Time :2587

Microsoft Word can read text files - so why not read the text file into an Interop Word Document & then convert by using one of the SaveAs methods.

I tested with a 34Mb, 1000000 line text file - the result was a 22Mb DOCX file:

MSWord.Application appAC = new MSWord.Application();
MSWord.Document doc = appAC.Documents.Open("TestRead.txt");
doc.SaveAs2(FileName:"TestSave", FileFormat:WdSaveFormat.wdFormatDocumentDefault);
doc.Close();
appAC.Quit();

Note that Microsoft states a maximum document size of 32MB - the text file exceeded this, but the resulting DOCX file was smaller - your exception maybe related to the size of the final file.

Related