IsolatedStorageFile

  • 2520
  • 0

IsolatedStorageFile

 

IsolatedStorageFile

 

問題與場景:

 

需要將使用者資訊或應用程式設定值以隔離及安全的方式作存取

 

解法:

 

isolatedStorageFile : 表示含有檔案和目錄的隔離儲存區(Isolated Storage)。

命名空間:  System.IO.IsolatedStorage
組件:  mscorlib (在mscorlib.dll 中)

隔離儲存區介紹

案例

 

使用方法:

 

假如你只要簡單使用隔離儲存區存取使用者資訊

 

可以使用以下這個類別

 

    public class SimpleIsolatedStoreFile<T> 
    {
        
        private readonly string _fileName;

        private IsolatedStorageFile _isoStore;

        public SimpleIsolatedStoreFile(string pFileName) 
        {
            if (String.IsNullOrEmpty(pFileName)) 
            {
                throw new ArgumentNullException("pFileName");
            }
            this._fileName = pFileName;
            this._isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
        }

        public SimpleIsolatedStoreFile Save(T pObj)
        {
            using (Stream stream = new IsolatedStorageFileStream(this._fileName, FileMode.Create, this._isoStore))
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                formatter.Serialize(stream, pObj);
            }
            return this;
        }

        public T Read()
        {
            using (Stream stream = new IsolatedStorageFileStream(this._fileName, FileMode.OpenOrCreate, this._isoStore))
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                if (stream.Length == 0)
                {
                    return default(T);
                }
                return (T)formatter.Deserialize(stream);
            }
        }
    }

使用範例:

 

Save

SimpleIsolatedStoreFile<DeployOption> isoStore= new SimpleIsolatedStoreFile<DeployOption>(FILE_NAME);

            isoStore.Save(this._option);

 

Read

SimpleIsolatedStoreFile<DeployOption> isoStore= new SimpleIsolatedStoreFile<DeployOption>(FILE_NAME);

            vardeploy= isoStore.Read();

            this.Option= deploy?? newDeployOption();

 

 

其他:

 

歡迎自行擴充與修改

分享