WindowsPhone 7目录和文件操作
1.Wp的IsolatedStorage文件存储机制:
Wp的文件存储机制是完全独立的,用户可以随时进行常见的IO操作,如增 删 查 改 。为wp7提供这一模式的基类是Silverlight for windowsphone 7中的IsolatedStrorage(独立存储),该类位于 System.IO.IsolatedStorage 命名空间里,同事System.IO.IsolatedStorage 命名空间有赖于System.IO 命名空间,只有这两者的参与,才能实现想过的文件操作。
文件操作需要遵循的步骤:
a. 首先需要或许用户的独立存储空间,可以使用IsolatedStorageFile 基类的GetUserStoreForApplication()方法获取,然后就可以进行相关的的操作 例如:IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication()
b. 利用返回的对象,使用该对象提供的相关方法进行先关操作,例如file.DirectoryExists(“这里是文件名,string类型”)检查文件是否存在。
c. 文件操作结束之后要将该文件关闭,再放回独立存储空间里
d. 切记要使用try catch 来捕捉异常IsolatedStorageException。
IsolatedStorage重要类如下:
1) IsolatedStorageFile:用于操作独立存储空间里的目录及其文件。
2)IsolatedStorageFileStream:用于读写操作的相关输入流.
3) IsolatedStorageSettings:用于存储应用程序配置信息的Dictionary。
Demo:
1.在页面中拖拽如相关的控件
2.编写后台的c#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
namespace Test
{
public partial class MainPage : PhoneApplicationPage
{
// 构造函数
public MainPage()
{
InitializeComponent();
Checkbutton.Click+=new RoutedEventHandler(Checkbutton_Click);
}
private const string dir="Mydir";
private void Checkbutton_Click(object sender, RoutedEventArgs e)
{
try
{
//这里获取到用户的独立存储空间
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
if (file.DirectoryExists(dir))
{
MessageBox.Show("目录存在");
}
else
MessageBox.Show("目录不存在");
}
}
catch(IsolatedStorageException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}