Skip to main content
 首页 » 编程设计

c#之将富文本文档保存到 Windows 应用商店应用程序中的临时文件夹

2024年02月13日12TianFang

我正在尝试将 RichEditBox 的内容保存到我的应用程序临时文件夹中,但我无法让它工作。

这是通过“保存文件”选择器将文件保存到磁盘的工作代码:

// [code for savePicker. Not relevant because that all works fine] 
StorageFile file = await savePicker.PickSaveFileAsync(); 
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite); 
editor.Document.SaveToStream(TextGetOptions.FormatRtf, stream); 

这是将 txt 文件保存到临时存储器的工作代码

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.txt",  
                         CreationCollisionOption.ReplaceExisting); 
await FileIO.WriteTextAsync(file, "some text"); 

所以当我将这些组合起来将 RTF 内容保存到临时文件夹时,这就是我写的:

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.rtf",  
                         CreationCollisionOption.ReplaceExisting); 
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite); 
editor.Document.SaveToStream(TextGetOptions.FormatRtf, stream); 

这行不通。我在第二行 StorageFile file = etc 上收到拒绝访问错误 (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))。然而,同一行代码在上面的第二个 block 中执行得很好。似乎当我用 file.OpenAsync 跟随它时它会抛出一个错误。有人可以在这里指出我正确的方向吗?和await有什么关系吗?

编辑:我接受并赞成 Damir Arh 的回答,因为它是解决此问题的正确方法。我的解决方法为我解决了这个问题,但 Damir Arh 的回答解决了问题的根本原因,当然这总是更好。

请您参考如下方法:

这段代码应该可以正常工作;我什至测试了它,只是为了确定:

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.rtf",  
                         CreationCollisionOption.ReplaceExisting); 
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite); 
editor.Document.SaveToStream(TextGetOptions.FormatRtf, stream); 

您错误地确定了失败的原因。 CreateFileAsync 不会失败,因为它后面跟着 OpenAsync;后者在失败时甚至没有开始执行。

最可能的原因是您已经从未正确关闭的 Stream 打开它。即使使用您在答案中发布的代码,这种情况仍然会发生。

我建议您使用 CreationCollisionOption.GenerateUniqueName 而不是 CreationCollisionOption.ReplaceExisting。这样,如果由于某种原因不能使用原始文件名,将创建一个具有不同名称的文件。

还要确保在完成写入后正确关闭流。由于 IRandomAccessStream 实现了 IDisposable,因此当您不再需要它时,您应该始终对其调用 Dispose。甚至更好:将它放在一个 using block 中,它将为您执行此操作。

这是应用了这两个更改的代码:

StorageFolder temp = ApplicationData.Current.TemporaryFolder; 
StorageFile file = await temp.CreateFileAsync("temp.rtf", 
                            CreationCollisionOption.GenerateUniqueName); 
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) 
{ 
    Editor.Document.SaveToStream(TextGetOptions.FormatRtf, stream); 
    await stream.FlushAsync(); 
}