本文讨论Windows Phone 8&8.1独立储存区一般文件操作,即字符文件(图片、声音不包括)的操作。
参考资料:《Windows Phone 8开发技巧与案例精解》周家安著 第8章 独立存储与I/O
周老师的CSDN博客地址:http://blog.csdn.net/tcjiaan
还有一篇博文:http://blog.csdn.net/whuarui2010/article/details/7639818
当然,微软官方的文章看看也是极好的:http://msdn.microsoft.com/ZH-CN/library/ff402541(v=vs.92).aspx
Windows Phone 为每个应用分配一个独立存储区,这个独立存储区非常安全,只有应用本身可以读写,存放在目录:
C:\Data\Users\DefApps\AppData\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\Local
{xxxxxx}就是应用的唯一标识,这个目录会随着应用程序删除,所以小伙伴们只管放心测试,不会对手机和其他应用数据有影响,卸载程序时就会被完全删除的。
XAML文件:
<phone:PhoneApplicationPage
x:Class="FileTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<phone:Panorama>
<!--目录操作-->
<phone:PanoramaItem Header="目录操作">
<phone:PanoramaItem.HeaderTemplate>
<DataTemplate >
<TextBlock Text="{Binding}" FontSize="50"/>
</DataTemplate>
</phone:PanoramaItem.HeaderTemplate>
<Grid x:Name="ContentPanel" Margin="0,-38,0,0">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Button Content="列出所有文件" Click="SetDir_Click"/>
<Button Content="新建" Click="CreatDir"/>
</StackPanel>
<ListBox x:Name="dirlist">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" FontSize="30"/>
<Button Tag="{Binding}" Content="删" Click="DeleteDir"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</phone:PanoramaItem>
<!--文件操作-->
<phone:PanoramaItem Header="文件操作">
<phone:PanoramaItem.HeaderTemplate>
<DataTemplate >
<TextBlock Text="{Binding}" FontSize="50"/>
</DataTemplate>
</phone:PanoramaItem.HeaderTemplate>
<StackPanel Orientation="Vertical" Margin="0,-38,0,0">
<StackPanel Orientation="Horizontal">
<Button Content="创建" Click="CreatFile"/>
<Button Content="读取" Click="ReadFile"/>
<Button Content="列表" Click="SetFile_Click"/>
</StackPanel >
<Grid Background="Green">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="5*"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="文件列表" Grid.Row="0"/>
<ListBox x:Name="filelist" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" />
<Button Content="删" Click="DeleteFile" Tag="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Text="文件读取结果" Grid.Row="2"/>
<Grid Background="Blue" Grid.Row="3">
<TextBlock x:Name="content" Text="{Binding}" Grid.Row="1" Foreground="Red"/>
</Grid>
</Grid>
</StackPanel>
</phone:PanoramaItem>
<!--setting词条-->
<phone:PanoramaItem Header="setting词条">
<phone:PanoramaItem.HeaderTemplate>
<DataTemplate >
<TextBlock Text="{Binding}" FontSize="50"/>
</DataTemplate>
</phone:PanoramaItem.HeaderTemplate>
<StackPanel Orientation="Vertical" Margin="0,-38,0,0">
<StackPanel Orientation="Horizontal">
<Button Content="添加" Click="AddSetting"/>
<Button Content="读取" Click="ReadSetting"/>
<Button Content="删除" Click="DeleteSetting"/>
<Button Content="移除所有" Click="DeleteAll"/>
</StackPanel>
<TextBlock Text="读取结果:"/>
<TextBox x:Name="textbox" Text="{Binding}" TextWrapping="Wrap"/>
</StackPanel>
</phone:PanoramaItem>
</phone:Panorama>
</phone:PhoneApplicationPage>
*.cs文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using FileTest.Resources;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
namespace FileTest
{
public partial class MainPage : PhoneApplicationPage
{
// 构造函数
public MainPage()
{
InitializeComponent();
}
//文件夹目录操作
// 列出所有目录
private void SetDir()
{
// 获取独立储存区
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
// 获得所有目录名称
string[] dir = iso.GetDirectoryNames();
// 将所有目录名称显示在列表中
this.dirlist.ItemsSource = dir;
}
}
private void SetDir_Click(object sender, RoutedEventArgs e)
{
SetDir();
}
// 创建目录
private void CreatDir(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
// 判断文件目录是否存在
if (iso.DirectoryExists("文件夹") == false)
{
// 创建文件目录
iso.CreateDirectory("文件夹");
MessageBox.Show("创建成功");
SetDir();
}
}
}
// 删除目录
private void DeleteDir(object sender, RoutedEventArgs e)
{
// 获取点击项
Button btn = e.OriginalSource as Button;
if (btn != null)
{
// 通过点击项的Tag 获得文件目录
string dirname = (string)btn.Tag;
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
if(! iso.DirectoryExists(dirname))
{
return;
}
try
{
// 删除目录
iso.DeleteDirectory(dirname);
MessageBox.Show("删除成功");
SetDir();
}
catch
{
MessageBox.Show("删除失败");
}
// 释放资源
iso.Dispose();
}
}
// 文件操作
// 列出所有文件
private void SetFile()
{
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
// 获取所有文件名称
string[] file = iso.GetFileNames();
this.filelist.ItemsSource = file;
}
}
private void SetFile_Click(object sender, RoutedEventArgs e)
{
SetFile();
}
// 创建文件,并向文件写入内容,FileMode的类型是覆盖
private void CreatFile(object sender, RoutedEventArgs e)
{
try
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// 创建文件流,FileMode决定是Create还是Append等
using (IsolatedStorageFileStream fs = iso.OpenFile(("file.txt"),FileMode.Create, FileAccess.Write,FileShare.Write))
{
// 定义文件写入流,编码方式是UTF-8
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
// 向文件写入内容,末尾不带换行符
sw.Write("这是我的第一个文件");
// 向文件内容添加一行,行尾会自己带上换行符
//sw.WriteLine("第一行");
//sw.WriteLine("第二行");
sw.Flush();
sw.Close();
MessageBox.Show("文件写入成功!");
// fs.Close();
}
}
catch
{
MessageBox.Show("文件写入失败!");
}
}
// 读取文件内容
private void ReadFile(object sender, RoutedEventArgs e)
{
try
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
if (iso.FileExists("file.txt"))
{
using (IsolatedStorageFileStream fs = iso.OpenFile("file.txt", FileMode.Open, FileAccess.Read))
{
// 创建文件读取流
StreamReader sr = new StreamReader(fs,Encoding.UTF8);
// 一直读到末尾
string s = sr.ReadToEnd();
// 读取一行,知道回车处停止
//string s = sr.ReadLine();
// 在前面的基础上读取后面的一行
//s = sr.ReadLine();
sr.Close();
this.content.Text = s;
}
}
}
catch
{
MessageBox.Show("文件读取失败");
}
}
// 删除文件
private void DeleteFile(object sender, RoutedEventArgs e)
{
Button btn = e.OriginalSource as Button;
if (btn == null)
return;
string filename = (string)btn.Tag;
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
if (!iso.FileExists(filename))
return;
try
{
iso.DeleteFile(filename);
MessageBox.Show("删除成功");
SetFile();
}
catch
{
MessageBox.Show("删除失败");
SetFile();
}
}
//setting词条操作
// 增加词条
private void AddSetting(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings isoset = IsolatedStorageSettings.ApplicationSettings;
string settingname = "name";
string settingvalue = "value";
// 判断词条是否存在
if (isoset.Contains(settingname))
{
MessageBox.Show("设置已经存在");
//更新词条的值,同时Add的时候也可直接使用此方法,存在则覆盖,否则创建
//isoset[settingname] = settingvalue;
return;
}
// 通过词条名添加词条值
isoset.Add(settingname, settingvalue);
// isoset[settingname] = settingvalue;
// 保存词条,否则重启是数据丢失
isoset.Save();
MessageBox.Show("新setting添加成功");
}
// 读取词条
private void ReadSetting(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings isoset = IsolatedStorageSettings.ApplicationSettings;
string settingname = "name";
string settingvalue = "";
if (isoset.Contains(settingname))
{
// 通过词条名读取词条
settingvalue = isoset[settingname].ToString();
this.textbox.Text = settingvalue;
}
else
MessageBox.Show("设置不存在");
}
// 删除指定词条
private void DeleteSetting(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings isoset = IsolatedStorageSettings.ApplicationSettings;
string settingname = "name";
if (isoset.Contains(settingname))
{
// 通过词条名删除指定词条
isoset.Remove(settingname);
MessageBox.Show("删除成功");
}
else
MessageBox.Show("删除失败");
}
// 移除所有词条
private void DeleteAll(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings isoset = IsolatedStorageSettings.ApplicationSettings;
// 移除所有词条,通常用于重置设置
isoset.Clear();
// 如果是重置,则在此处重新加入默认的词条
MessageBox.Show("已经移除所有设置");
}
}
}
整个就是三大部分:目录操作(Dir)、文件操作(File)、设置词条(setting)
关于Setting:
“设置词条”是wp的一大特色,操作起来相当方便,一条设置包括词条名(Name)和词条值(Value),设置单独作为文件的一部分,要添加一条就直接Add,移除就Remove,全部重置就Clear,妈妈再也不用担心我们为了小小的设置去研究复杂的文件操作了!
哦,最后说一下关于8.1API变化的看法,实际上我们只需要在新建工程是选择Windows Phone Silverlight应用程序就可以了,兼容8和8.1,使用的是之前的API,当然其实也就改了几个名字啦,记住了那么多的属性和方法,这几个算什么,哈哈。
代码下载地址:
http://download.csdn.net/detail/chiyiw/7811443