IsolatedStorageSettings
因为它所提供的功能很有限, 而隔离存储所提供的是一整套本地存储的方案,包括目录,文件管理等方面.
本文将会继续上文中的内容,通过一个本地文件系统管理的DEMO来演示一下如果使用下面两个隔离存储类:
IsolatedStorageFileStream (以流的方式读写指定路径的文件)
首先请大家看一下这个DEMO的演示效果:
![在silverlight中使用IsolateStore隔离存储(下) _存储](http://daizhj.cnblogs.com/p_w_picpaths/cnblogs_com/daizhj/silverlight_isolate_store_stream.jpg)
我们可以在这里进行目录的选择,文件的选择,以及在相应的目录下添加,编辑,删除工作.而实现这些功能
都用到了上面所说的两个类.
CreateDirectory() //创建路径 Creates a directory in the isolated storage scope.
CreateFile() //创建文件 Creates a file in the isolated store.
DeleteDirectory()//删除路径 Deletes a directory in the isolated storage scope.
DeleteFile() //删除文件
GetFileNames //获取指定路径下的文件列表
DirectoryExists()
FileExists()
使用如下方法将其绑定了一个读或写的流对象上:
using (StreamWriter writer = new StreamWriter(subDraftFile))
{
//
![在silverlight中使用IsolateStore隔离存储(下) _职场_02](http://www.cnblogs.com/Images/dot.gif)
![在silverlight中使用IsolateStore隔离存储(下) _职场_02](http://www.cnblogs.com/Images/dot.gif)
}
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.307*"/>
<ColumnDefinition Width="0.176*" />
<ColumnDefinition Width="0.517*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="231"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="0" Grid.RowSpan="4" Background="AliceBlue" >
<TextBlock Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" Margin="5,5,5,5">
<Run Text="路径:"/>
</TextBlock>
<ListBox x:Name="DirectoryList" SelectionChanged="DirectoryList_SelectionChanged" Margin="5,5,5,5"/>
<TextBlock Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" Margin="5,5,5,5">
<Run Text="文件列表:"/>
</TextBlock>
<ListBox x:Name="FileList" SelectionChanged ="FileList_SelectionChanged" Margin="5,5,5,5" Height="150"/>
</StackPanel>
<TextBlock Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" Margin="5,5,5,5">
<Run Text="收件人:"/>
</TextBlock>
<TextBox x:Name="Recipient" Width="200" Grid.Row="0" Grid.Column="2" Margin="5,5,5,5" HorizontalAlignment="Left" d:LayoutOverrides="GridBox"/>
<TextBlock Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" Margin="5,5,5,5">
<Run Text="主 题:"/>
</TextBlock>
<TextBox x:Name="Subject" Width="200" Grid.Row="1" Grid.Column="2" Margin="5,5,5,5" HorizontalAlignment="Left" d:LayoutOverrides="GridBox"/>
<TextBlock Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch" Margin="5,5,5,5">
<Run Text="内 容:"/>
</TextBlock>
<TextBox x:Name="Body" TextWrapping="Wrap" Grid.Row="2" Grid.Column="2" Margin="5,5,5,5" HorizontalAlignment="Stretch" Grid.RowSpan="1" d:LayoutOverrides="GridBox" RenderTransformOrigin="0.5,0.5">
</TextBox>
<StackPanel Grid.Row="3" Orientation="Horizontal" Grid.Column="1" Grid.ColumnSpan="2" Margin="0,0,0,8">
<Button x:Name="AddToDraft" Margin="5,5,5,5" Content=" 添加草稿 " Click="AddToDraft_Click" />
<Button x:Name="SaveToDraft" Margin="5,5,5,5" Content=" 编辑草稿 " Click="SaveToDraft_Click" />
<Button x:Name="DeleteDraft" Margin="5,5,5,5" Content=" 删除当前草稿 " Click="DeleteDraft_Click"/>
</StackPanel>
</Grid>
而相应的page.xaml.cs文件如下(相关内容见注释):
{
public Page()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
{
//如果本地没有文件夹,则初始化本地文件夹信息
if (!store.DirectoryExists("本地文件夹"))
{
// 在当前根目录下创建三个目录
store.CreateDirectory("本地文件夹");
// 可使用下面方面在指定目录下创建子目录
store.CreateDirectory(System.IO.Path.Combine("本地文件夹", "收件箱"));
store.CreateDirectory(System.IO.Path.Combine("本地文件夹", "发件箱"));
store.CreateDirectory(System.IO.Path.Combine("本地文件夹", "草稿箱"));
}
//加载文件夹信息到控件
foreach (string directory in GetAllDirectories("*", store))
{
DirectoryList.Items.Add(directory);
}
}
}
/// <summary>
/// 添加数据到草稿箱
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddToDraft_Click(object sender, RoutedEventArgs e)
{
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
{
string filePath = DirectoryList.SelectedItem.ToString();
if (store.DirectoryExists(filePath))
{
filePath = System.IO.Path.Combine(filePath, Subject.Text + ".txt");
if (!store.FileExists(filePath))
{
IsolatedStorageFileStream subDraftFile = store.CreateFile(filePath);
using (StreamWriter writer = new StreamWriter(subDraftFile))
{
writer.WriteLine("Recipient:" + Recipient.Text);
writer.WriteLine("Subject:" + Subject.Text);
writer.WriteLine("Body:" + Body.Text);
}
subDraftFile.Close();
}
else
{
HtmlPage.Window.Alert("文件已存在,请修改主题后再进行保存");
}
}
}
}
/// <summary>
/// 保存草稿箱的数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToDraft_Click(object sender, RoutedEventArgs e)
{
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
{
string filePath = DirectoryList.SelectedItem.ToString() + "/" + FileList.SelectedItem.ToString();
if (store.FileExists(filePath))
{
store.DeleteFile(filePath);
IsolatedStorageFileStream subDraftFile = store.CreateFile(filePath);
using (StreamWriter writer = new StreamWriter(subDraftFile))
{
writer.WriteLine("Recipient:" + Recipient.Text);
writer.WriteLine("Subject:" + Subject.Text);
writer.WriteLine("Body:" + Body.Text);
}
subDraftFile.Close();
}
else
{
HtmlPage.Window.Alert("要修改的当前文件不在本地隔离存储!!!");
}
}
}
/// <summary>
/// 删除指定草稿
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DeleteDraft_Click(object sender, RoutedEventArgs e)
{
if (FileList.SelectedItem != null)
{
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
{
string filePath = DirectoryList.SelectedItem.ToString() + "/" + FileList.SelectedItem.ToString();
if (store.FileExists(filePath))
{
if (HtmlPage.Window.Confirm("是否删除文件: " + filePath))
{
store.DeleteFile(filePath);
}
}
}
}
}
/// <summary>
/// 分割字符串
/// </summary>
public static string[] SplitString(string strContent, string strSplit)
{
if (strContent != null && strContent != "")
{
if (strContent.IndexOf(strSplit) < 0)
{
string[] tmp = { strContent };
return tmp;
}
return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
}
else
{
return new string[0] { };
}
}
/// <summary>
/// 下面代码从网上获得,用于递归指定路径下的所有目录
/// </summary>
/// <param name="pattern"></param>
/// <param name="storeFile"></param>
/// <returns></returns>
public string[] GetAllDirectories(string pattern, System.IO.IsolatedStorage.IsolatedStorageFile storeFile)
{
// Get the root of the search string.
string root = System.IO.Path.GetDirectoryName(pattern);
if (root != "") root += "/";
// Retrieve directories.
string[] directories;
directories = storeFile.GetDirectoryNames(pattern);
List<string> directoryList = new List<string>(directories);
// Retrieve subdirectories of matches.
for (int i = 0, max = directories.Length; i < max; i++)
{
string directory = directoryList[i] + "/";
string[] more = GetAllDirectories(root + directory + "*", storeFile);
// For each subdirectory found, add in the base path.
for (int j = 0; j < more.Length; j++)
more[j] = directory + more[j];
// Insert the subdirectories into the list and
// update the counter and upper bound.
directoryList.InsertRange(i + 1, more);
i += more.Length;
max += more.Length;
}
return (string[])directoryList.ToArray();
}
/// <summary>
/// 下面代码从网上获得,用于递归指定路径下的所有文件
/// </summary>
/// <param name="pattern"></param>
/// <param name="storeFile"></param>
/// <returns></returns>
public string[] GetAllFiles(string pattern, System.IO.IsolatedStorage.IsolatedStorageFile storeFile)
{
// Get the root and file portions of the search string.
string fileString = System.IO.Path.GetFileName(pattern);
string[] files;
files = storeFile.GetFileNames(pattern);
List<string> fileList = new List<string>(files);
// Loop through the subdirectories, collect matches,
// and make separators consistent.
//foreach (string directory in GetAllDirectories("*", storeFile))
// foreach (string file in storeFile.GetFileNames(directory + "/" + fileString))
// fileList.Add((directory + "/" + file));
return (string[])fileList.ToArray();
}
/// <summary>
/// 当用户选择不同的路径时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DirectoryList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FileList.Items.Clear();
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string file in GetAllFiles(DirectoryList.SelectedItem.ToString() + "/", store))
{
FileList.Items.Add(file);
}
}
}
/// <summary>
/// 当用户选择相应的文件时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FileList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(FileList.SelectedItem != null)
{
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
{
string filePath = System.IO.Path.Combine(DirectoryList.SelectedItem.ToString(), FileList.SelectedItem.ToString());
if (store.FileExists(filePath))
{
IsolatedStorageFileStream subDraftFile =
store.OpenFile(filePath, FileMode.Open);
//加载指定文件中的内容
using (StreamReader reader = new StreamReader(subDraftFile))
{
string[] emailInfo = SplitString(reader.ReadToEnd(), "\r\n");
foreach (string emailItem in emailInfo)
{
if (emailItem.IndexOf("Recipient") >= 0)
{
Recipient.Text = emailItem.Split(':')[1]; continue;
}
if (emailItem.IndexOf("Subject") >= 0)
{
Subject.Text = emailItem.Split(':')[1]; continue;
}
if (emailItem.IndexOf("Body") >= 0)
{
Body.Text = emailItem.Split(':')[1]; continue;
}
}
}
subDraftFile.Close();
}
else
{
HtmlPage.Window.Alert("文件: " + filePath + " 不存在!!!");
}
}
}
}
}
其实就我个人而言,我是不太建议过于频繁的使用Isolate Store, 当然主要是出于安全问题的考虑(
因为我本人对它的机制还不是很了解,所以不便妄加评论), 但我本人还是比较偏向于下面这篇文章中的观
点:
好了,今天的内容就先到这里了:)
源代码下载链接, 请点击这里:)