ev.shevnun
ev.shevnun

Reputation: 11

Issue with creating a .doc file and writing text to it

Task:
The task is to insert a string of any length into a new .doc (not .docx) file. This means creating a new .doc file and writing my string into it. I tried using the NuGet package NPOI.HWPF for this task (example below).

I encountered the issue that in order to create a new file, it needs to open an existing file as a template to write text into, and then save the file as a new one. However, if there is no space for text in the template, it won’t write anything.

Additionally, I constantly receive the message when trying to run the program:

A property claimed to end (29) before start! Resetting end to start, and hoping for the best.

Could you help me figure out how to solve this task? I'm open to using other libraries, but they must not require a license.

using NPOI.HWPF;
namespace ConsoleApp4;

class Program
{
    static void Main(string[] args)
    {
        string filePathEmptyDoc = "/home/evgeniy/test/empty.doc";
        string filePathNewDoc = "/home/evgeniy/test/newDoc.doc";
        string content = "test text";

        using (FileStream fs = new FileStream(filePathEmptyDoc, FileMode.Open, FileAccess.Read))
        {
            NPOI.HWPF.HWPFDocument doc = new HWPFDocument(fs);
            
            NPOI.HWPF.UserModel.Range range = doc.GetRange();

            range.InsertBefore(content);

            using (FileStream ofs = new FileStream(filePathNewDoc, FileMode.Create, FileAccess.Write))
            {
                doc.Write(ofs);
            }
        }
    }
}

I attempted to use the NuGet package NPOI.HWPF to create a new .doc file and insert a string of any length into it

Upvotes: 1

Views: 67

Answers (0)

Related Questions