详解Silverlight 2中的独立存储(Isolated Storage)
[1] 详解Silverlight 2中的独立存储(Isolated Storage)
[2] 详解Silverlight 2中的独立存储(Isolated Storage)
[3] 详解Silverlight 2中的独立存储(Isolated Storage)
[4] 详解Silverlight 2中的独立存储(Isolated Storage)
[5] 详解Silverlight 2中的独立存储(Isolated Storage)
[6] 详解Silverlight 2中的独立存储(Isolated Storage)
[7] 详解Silverlight 2中的独立存储(Isolated Storage)
[2] 详解Silverlight 2中的独立存储(Isolated Storage)
[3] 详解Silverlight 2中的独立存储(Isolated Storage)
[4] 详解Silverlight 2中的独立存储(Isolated Storage)
[5] 详解Silverlight 2中的独立存储(Isolated Storage)
[6] 详解Silverlight 2中的独立存储(Isolated Storage)
[7] 详解Silverlight 2中的独立存储(Isolated Storage)
下面来看各个功能的实现:
创建目录,直接使用CreateDirectory方法就可以了,另外还可以使用DirectoryExistes方法来判断目录是否已经存在:
void btnCreateDirectory_Click(object sender, RoutedEventArgs e) { using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { String directoryName = this.txtDirectoryName.Text; if (this.lstDirectories.SelectedItem != null) { directoryName = System.IO.Path.Combine(this.lstDirectories.SelectedItem.ToString(), directoryName); } if (!store.DirectoryExists(directoryName)) { store.CreateDirectory(directoryName); HtmlPage.Window.Alert("创建目录成功!"); } } }
创建文件,通过CreateFile方法来获取一个IsolatedStorageFileStream,并将内容写入到文件中:
void btnCreateFile_Click(object sender, RoutedEventArgs e) { if (this.lstDirectories.SelectedItem == null && this.txtDirectoryName.Text == "") { HtmlPage.Window.Alert("请先选择一个目录或者输入目录名"); return; } using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { String filePath; if (this.lstDirectories.SelectedItem == null) { filePath = System.IO.Path.Combine(this.txtDirectoryName.Text, this.txtFileName.Text + ".txt"); } else { filePath = System.IO.Path.Combine(this.lstDirectories.SelectedItem.ToString(), this.txtFileName.Text + ".txt"); } IsolatedStorageFileStream fileStream = store.CreateFile(filePath); using (StreamWriter sw = new StreamWriter(fileStream)) { sw.WriteLine(this.txtFileContent.Text); } fileStream.Close(); HtmlPage.Window.Alert("写入文件成功!"); } }
读取文件,直接使用System.IO命名空间下的StreamReader:
void btnReadFile_Click(object sender, RoutedEventArgs e) { if (this.lstDirectories.SelectedItem == null || this.lstFiles.SelectedItem == null) { HtmlPage.Window.Alert("请先选择目录和文件!"); return; } using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { String filePath = System.IO.Path.Combine(this.lstDirectories.SelectedItem.ToString(), this.lstFiles.SelectedItem.ToString()); if (store.FileExists(filePath)) { StreamReader reader = new StreamReader(store.OpenFile(filePath, FileMode.Open, FileAccess.Read)); this.txtFileContent.Text = reader.ReadToEnd(); this.txtDirectoryName.Text = this.lstDirectories.SelectedItem.ToString(); this.txtFileName.Text = this.lstFiles.SelectedItem.ToString(); } } }