IsolatedStorage
根目录
----shared
----Media
----ShellContent
----Transfers
using System.IO.IsolatedStorage;
写入操作
1.创建IsolatedStorageFile对象,并创建文件夹(目录)。
2.创建IsolatedStorageFileStream对象,传入Stream流给StreamWriter,写入文件。
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); isf.CreateDirectory("Folder"); // IsolatedStorageFileStream - 独立存储内的文件流。继承自 FileStream using (var isfs = new IsolatedStorageFileStream(@"Folder\File.txt", FileMode.OpenOrCreate, isf)) { using (var sw = new StreamWriter(isfs)) { sw.WriteLine("hello webabcd"); } }
读取操作
使用StreamReader读取即可
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); try { // IsolatedStorageFileStream - 独立存储内的文件流。继承自 FileStream using (var isfs = new IsolatedStorageFileStream(@"Folder\File.txt", FileMode.Open, isf)) { using (var sr = new StreamReader(isfs)) { MessageBox.Show(sr.ReadLine()); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); }
读/写 key/value 形式数据到独立存储的快捷方法
IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings; // 用这种方法保存 key/value 形式的数据非常简单 iss["abc"] = "webabcd"; // 保存 IsolatedStorageSettings 数据,但是经过测试,即使不调用此方法,数据也会被保存。但是为了保险还是调用一下 Save() 比较好 iss.Save(); IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings; // 用这种方法读取 key/value 形式的数据非常简单 if (iss.Contains("abc")) MessageBox.Show((string)iss["abc"]);
下载网络文件保存到独立储存
public MainPage() { InitializeComponent(); using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { //先检验文件是否存在,存在就删除 if (myIsolatedStorage.FileExists(isf)) { myIsolatedStorage.DeleteFile(isf); } else { WebClient webClient = new WebClient(); webClient.OpenReadCompleted += OnWebClientOpenReadCompleted; webClient.OpenReadAsync(new Uri("http://mp3.baidu.com/....mp3")); } } } string isf = "text.mp3"; //下载文件的名称+后缀名 // 当文件下载完成,写入独立储存 void OnWebClientOpenReadCompleted(object sender,OpenReadCompletedEventArgs args) { if (!args.Cancelled && args.Error == null) { Stream inpStream = args.Result; byte[] buffer = new byte[inpStream.Length]; //写入buffer inpStream.Read(buffer, 0, buffer.Length); using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { string isoPathName = isf; string isoDirName = Path.GetDirectoryName(isoPathName); if (!isoStore.DirectoryExists(isoDirName)) { isoStore.CreateDirectory(isoDirName); } using (IsolatedStorageFileStream isoStream = isoStore.CreateFile(isoPathName)) { isoStream.Write(buffer, 0, buffer.Length); //PS: Stream.Write与StreamWriter.Write写入文件,大小可能不同,后者可能多输出文件的BOM,多出几个字节 } } }