UWP文件读写--遇到的坑

参考了这篇文章----http://blog.csdn.net/lindexi_gd/article/details/49007841

一开始使用了.net最早的FileStrem类保存

1 using (FileStream fs = new FileStream("F:\\" + cons[1], FileMode.Create))
2 {
3 fs.Write(ic.Byte_data, 0, ic.Byte_data.Length);
4 fs.Dispose();
5 }

PS:UWP的FileStream类没有Close方法,只有Dispose方法。

结果始终无法保存文件。后来用了提及文章中微软推荐方法来保存,如下

 1 StorageFolder folder;
 2                     folder = ApplicationData.Current.LocalFolder; // await StorageFolder.GetFolderFromPathAsync("F:\\");
 3                     StorageFile file = await folder.CreateFileAsync(cons[1],CreationCollisionOption.ReplaceExisting);
 4                     using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
 5                     {
 6                         using (DataWriter dataWriter = new DataWriter(transaction.Stream))
 7                         {
 8                             dataWriter.WriteBytes(ic.Byte_data);
 9                             //dataWriter.WriteString(str);
10                             transaction.Stream.Size = await dataWriter.StoreAsync();
11                             await transaction.CommitAsync();
12                         }
13                     }

这样文件保存在了C:\Users\......\AppData\Local\Packages\cef74189-c77c-4412-ae8c-117f5d452d49_8y2ny6xz671t0\LocalState中。

代码注释的部分"await StorageFolder.GetFolderFromPathAsync("F:\\");"试图将文件保存在F盘下,但运行时报错

“WinRT 信息: 无法访问指定的文件或文件夹(F:\)。该项目没有位于应用程序可以访问的位置(包括应用程序数据文件夹、可通过许可范围进行访问的文件夹以及保存在 StorageApplicationPermissions 列表中的项目)中。请确认未使用系统或隐藏文件属性标记该文件。”

 

读取文件

StorageFolder folder = ApplicationData.Current.RoamingFolder;
StorageFile file = await folder.TryGetItemAsync("position.txt") as StorageFile;
 if (file != null)
{
        IBuffer ibuffer = await FileIO.ReadBufferAsync(file);
            using (DataReader dr = DataReader.FromBuffer(ibuffer))
            {
                byte[] Byte_data = new byte[dr.UnconsumedBufferLength];
                dr.ReadBytes(Byte_data);             

            }
}

读取时先建立一个缓冲区IBuffer,然后从缓冲区建立一个DataReader,再从DataReader中读取需要的byte[]数据。需要说明的是,这里byte[]数组需要提前定义好长度,否则什么都读不出来。

posted @ 2017-05-11 20:27  不务正业的人  阅读(3575)  评论(3编辑  收藏  举报