1

我想在我的 UWP 应用程序中创建一个 Microsoft Word 文档,并且我已经成功地在 APP Local 文件夹中创建了 doc 文件。但我想在用户选择的特定文件夹位置创建这个 doc 文件。

我的意思是用户浏览一个位置,然后在该位置创建 doc 文件。

这是我在 App 本地路径中创建 Doc 文件的代码:

  string docFileName = "TestDoc.docx";
  Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

  string Filepath = localFolder.Path + "\\" + docFileName;

  using (var wordprocessingDocument = WordprocessingDocument.Create(file.Path, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
  {
      MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart();
      mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
      Body body = mainPart.Document.AppendChild(new Body());
      DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
      DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
      run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("Hello !!! ."));
      wordprocessingDocument.MainDocumentPart.Document.Save();
  }

尝试在特定位置创建 doc 文件时出现以下错误,如下所示:

错误

Message=媒体写保护:'D:\Training\TestDoc.docx'

代码

string path = @"D:\Training\TestDoc.docx";

using (var wordprocessingDocument = WordprocessingDocument.Create(path, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart();
    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
    Body body = mainPart.Document.AppendChild(new Body());
    DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
    DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
    run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("Hello !!! ."));
    wordprocessingDocument.MainDocumentPart.Document.Save();
}
4

1 回答 1

2

由于 UWP 应用在沙盒中运行,因此无法使用经典 API 直接访问文件系统路径。但是,您可以使用Windows.StorageAPI 来执行此操作。

让用户选择保存文件

如果你想让用户选择保存文件,你可以使用FileSavePickerAPI。此文档页面详细描述了这一点。完成后,API 将为您提供一个StorageFile实例,您可以使用该实例。

写入文件

由于您不能使用将Create文件路径作为参数的方法,因此您需要使用Stream基于路径的方法。

要从文件中获取Stream实例,请添加using System.IO;到代码文件的顶部,然后执行以下操作:

using(var stream = await file.OpenStreamForWriteAsync())

使用此流,您可以执行以下操作:

using (var wordprocessingDocument =
               WordprocessingDocument.Create(
                  stream, WordprocessingDocumentType.Document))
{
      //... your code
}

注意:广泛的文件系统访问

如果您确实需要在任意(不是用户选择的)位置创建文件,您可以使用broadFileSystemAccess功能. 然而,这仅适用于真正需要它的应用程序。请注意,即使具有此功能,您仍然需要使用StorageFileStorageFolderAPI 执行所有文件操作。

于 2020-01-07T13:19:01.523 回答