热搜:

WP7&WP8开发、文件读写操作上的区别

2013-06-08 15:34:13文章来源:点点软件园热度:0

更多

一、WP7的文件操作:

如果在wp7平台上去写入一个文件,我们会使用: IsolatedStorageFile

代码如下:

①写入文件
private void WriteFile(string fileName, string content)
{
using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.CreateFile(fileName))
{
using (StreamWriter streamWriter = new StreamWriter(isolatedStorageFileStream))
{
streamWriter.Write(content);
}
}
}
}
②读取文件
private string ReadFile(string fileName)
{
string text;
using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.OpenFile(fileName, FileMode.Open))
{
using (StreamReader streamReader = new StreamReader(isolatedStorageFileStream))
{
text = streamReader.ReadToEnd();
}
}
}
return text;
}
二、WP8文件操作

wp8与win8的文件操作方式类似,如果你在win8下写过文件操作,那么WP8自然熟悉,这需要用到2个接口:IStorageFile和 IStorageFolder, 可以看出,一个是对文件的操作,一个是对目录的。

这两个接口均在 :Windwos.Storage组件中,

注意:因在windows 8 开发中大量使用了WinRT异步编程方式,故在WP8中编程亦如此。

代码如下:

①写入文件:

public async Task WriteFile(string fileName, string text)
{
IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
IStorageFile storageFile = await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream stream = await storageFile.OpenStreamForWriteAsync())
{
byte[] content = Encoding.UTF8.GetBytes(text);
await stream.WriteAsync(content, 0, content.Length);
}
}
②读取文件:

public async Task<string> ReadFile(string fileName)
{
string text;
IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
IStorageFile storageFile = await applicationFolder.GetFileAsync(fileName);
IRandomAccessStream accessStream = await storageFile.OpenReadAsync();
using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
{
byte[] content = new byte[stream.Length];
await stream.ReadAsync(content, 0, (int) stream.Length);
text = Encoding.UTF8.GetString(content, 0, content.Length);
}
return text;
}
三、兼容性问题

上面的代码分别对WP7与WP8平台的文件写入与读取操作进行了简单的说明

那么在WP7应用中的文件目录结构定义,是不是在WP8中也是一样的呢?

其实,两者是有点区别的,这点区别,也是日后WP7向WP8迁移过程中必须要考虑的元素之一。

在WP7中,创建文件test.txt,那么,它在隔离存储区的文件目录结构如下:

C:\Data\Users\DefaultAppAccount\AppData\{ProductID}\Local\IsolatedStore\test.txt

在WP8中,创建相同文件,文件存储目录结构如下:

C:\Data\Users\DefaultAppAccount\AppData\{ProductID}\Local\test.txt

两者一对比,我们发现:在WP8开发中,如果使用现有的WP7代码时,如果你不想改变原有文件目录结构,那你就必须要首先获取WP7隔离存储目录.即:

IStorageFolder applicationFolder =await ApplicationData.Current.LocalFolder.GetFolderAsync("IsolatedStore");
最后,想说明的是:

如果你想“偷懒”或者说减少开发工作量,就看看我上面说的这些

但如果打算做WP8/WIN8两个平台,最好全新开发基于WP8平台的应用,这可以加快你的Win8应用的移植。更多最新IT资讯尽在金顺软件园http://www.jinshun168.com/

以上,就是金顺软件园小编给大家带来的WP7&WP8开发、文件读写操作上的区别全部内容,希望对大家有所帮助!

上一篇Photoshop CS6安装教程 ps6安装教程下一篇cf激情开火5倍经验游戏60分钟领礼包 高考报名玩家领取战场套装
编辑:点点小编
标签WP7WP8