发布创建的文件

时间:2013-02-23 14:56:51

标签: c# windows-8 windows-runtime

我有以下代码将Base64字符串转换为PDF文件,保存然后尝试打开它:

//Converts the Base64 data to bytes
byte[] bytes = Convert.FromBase64String(Base64String);

//Stores the converted Base64 data in the application's Local Resource directory, in PDF format
StorageFolder folder = ApplicationData.Current.LocalFolder;
string fileName = file.pdf";
CreationCollisionOption options = CreationCollisionOption.FailIfExists;

var file = await folder.CreateFileAsync(fileName, options);
var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
var outStream = fs.GetOutputStreamAt(0);
var dataWriter = new Windows.Storage.Streams.DataWriter(outStream);
dataWriter.WriteBytes(bytes);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
await outStream.FlushAsync();

string pdfPath = folder.Path + "\\" + fileName;

StorageFile fileToLaunch = await StorageFile.GetFileFromPathAsync(pdfPath);
await Windows.System.Launcher.LaunchFileAsync(fileToLaunch);

当文件在Adobe Reader中打开时,会显示一条消息,指出该文件仍在被其他应用程序使用。如何让我的应用程序“发布”该文件,以便Adobe可以打开它?请注意,这是一个Windows 8应用程序。

2 个答案:

答案 0 :(得分:3)

我怀疑这是问题所在:

var outStream = fs.GetOutputStreamAt(0);

IOutputStream扩展IDisposable,但您没有处理该流。尝试将代码的该部分更改为:

using (var outStream = fs.GetOutputStreamAt(0))
{
    var dataWriter = new Windows.Storage.Streams.DataWriter(outStream);
    dataWriter.WriteBytes(bytes);
    await dataWriter.StoreAsync();
    dataWriter.DetachStream();
    await outStream.FlushAsync();
}

答案 1 :(得分:1)

我必须将代码更改为以下内容:

        var file = await folder.CreateFileAsync(fileName, options);

        using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
        {
            using (var outStream = fs.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outStream))
                {
                    dataWriter.WriteBytes(bytes);
                    await dataWriter.StoreAsync();
                    dataWriter.DetachStream();
                    await outStream.FlushAsync();
                }
            }
        }