Здравия. Делаю простой редактор docx файлов (только текст). При попытке сохранить файл вылезает ошибка: System.Runtime.InteropServices.COMException: 'Приложению Word не удалось сохранить данный файл, так как он используется другим процессом.
Код функции сохранения:
Word._Application app = new Word.Application();
Word._Document word_doc = app.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
Word.Paragraph para = word_doc.Paragraphs.Add(ref oMissing);
para.Range.Text = text_editor.Text;
para.Range.InsertParagraph();
object filename = def_save_path;
word_doc.SaveAs2(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
object save_changes = false;
word_doc.Close(ref save_changes, oMissing, oMissing);
app.Quit(ref save_changes, oMissing, oMissing);
changed = false;
Пример для работы с OpenXML из документации, для его работы необходимо установить nuget пакет DocumentFormat.OpenXml
public static void CreateWordprocessingDocument(string filepath)
{
// Create a document by supplying the filepath.
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("Create text in body - CreateWordprocessingDocument"));
}
}
Результат
Сборка персонального компьютера от Artline: умный выбор для современных пользователей