zoukankan      html  css  js  c++  java
  • Windows Phone 独立存储之IsolatedStorageFile

    IsolatedStorageFile表示包含文件和目录的独立存储区。使用IsolatedStorageFile是一种让你可以在用户的设备中创建真实的文件和目录。

    该类使独立存储的虚拟文件系统抽象化。IsolatedStorageFile对象对应于特定的独立存储范围,在该范围中存在由 IsolatedStorageFileStream对象表示的文件。应用程序可以使用独立存储将数据保存在文件系统中这些数据自己的独立部分,而不必在文件系统中指定特定的路径。

    虚拟文件系统的根位于物理文件系统上经过模糊处理的每用户文件夹中。由主机提供的每个唯一标识符都映射为不同的根,该根为每个应用程序提供它自己的虚拟文件系统。应用程序不能从它自己的文件系统导航到另一个文件系统中。

    因为独立存储区在特定程序集的范围内,所以其他大多数托管代码都不能访问您的代码的数据(高度受信任的托管代码和管理工具可以从其他程序集访问存储区)。非托管代码可以访问任何独立存储区。

    1.获取独立存储IsolatedStorageFile对象
        IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
      2.创建目录
        myIsolatedStorage.CreateDirectory(path);
      3.创建文件
        myIsolatedStorage.CreateFile(path);
        注意:创建文件所在文件夹不存在时,无法创建成功。
      4.判断目录是否存在
        bool isExists = myIsolatedStorage.DirectoryExists(path);
      5.判断文件是否存在
        bool isExists = myIsolatedStorage.FileExists(path);
      6.删除文件
        myIsolatedStorage.DeleteFile(path);
      7.删除目录(需要递归实现)

    View Code
            /// <summary>
    /// 递归删除目录
    /// </summary>
    /// <param name="path">目录路径</param>
    /// <param name="myIsolatedStorage">独立存储</param>
    private static void rmDirAll(String path, IsolatedStorageFile myIsolatedStorage)
    {
    String searchPattern = path + "\\*";
    //查找该目录下所有子目录,递归删除之
    String[] dirs = myIsolatedStorage.GetDirectoryNames(searchPattern);
    for (int i = 0; i < dirs.Length; i++)
    {
    String dPath = path + "\\" + dirs[i];
    rmDirAll(dPath, myIsolatedStorage);
    }
    //查找该目录下所有文件,删除之
    String[] files = myIsolatedStorage.GetFileNames(searchPattern);
    for (int j = 0; j < files.Length; j++)
    {
    String fPath = path + "\\" + files[j];
    myIsolatedStorage.DeleteFile(fPath);
    }
    //该目录下所有子目录和文件都删除后才可删除该目录
    myIsolatedStorage.DeleteDirectory(path);
    }

    8.复杂文件
        myIsolatedStorage.CopyFile(srcFilename/*源文件*/, dstFilename/*目标文件*/, overwrite/*是否覆盖*/);
      9.读文件

    View Code
            if (myIsolatedStorage.FileExists(path))
    {
    //打开文件
    using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(path, FileMode.Open, FileAccess.Read))
    {
    using(StreamReader read = new StreamReader(fileStream))
    {
    String str = read.ReadToEnd();
    }
    }
    }

    10.写文件
        using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(path, fMode, myIsolatedStorage))
        {
          fileStream.Write(data, 0, size);
        }
      11.获取文件创建的日期
        DateTimeOffset offset = myIsolatedStorage.GetCreationTime(path);
        DateTime creatDate = offset.DateTime;

  • 相关阅读:
    BZOJ 4503: 两个串 FFT
    [FJOI2014]最短路径树问题
    [JSOI2009]游戏Game
    bzoj 2463 [中山市选2009]谁能赢呢?
    [CQOI2007]余数求和
    [NOI2011]兔兔与蛋蛋游戏
    [HNOI2015]实验比较
    bzoj2125 最短路
    [COGS 2877]老m凯的疑惑
    [HNOI2015]开店
  • 原文地址:https://www.cnblogs.com/huizhang212/p/IsolatedStorageFile.html
Copyright © 2011-2022 走看看