我想在UWP App中创建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();
}
尝试在如下所示的特定位置创建文档文件时出现以下错误:
错误
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();
}
由于UWP应用程序在沙箱中运行,因此您无法使用经典API直接访问文件系统路径。但是,您可以使用Windows.Storage
API来这样做。
如果要让用户选择保存文件,则可以使用FileSavePicker
API。此文档页面对此进行了详细说明。完成后,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
功能。但是,这仅适用于真正需要它的应用程序。请注意,即使具有此功能,您仍然需要使用StorageFile
和StorageFolder
API执行所有文件操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句