Inheritance: IsolatedStorage, IDisposable
Esempio n. 1
0
            public DynamicArchiveFileHandlerClass(IsolatedStorageFile isolatedStorageFile)
            {
                this.MaxArchiveFileToKeep = -1;
                this.isolatedStorageFile = isolatedStorageFile;

                archiveFileEntryQueue = new Queue<string>();
            }
Esempio n. 2
0
        internal IsolatedStorageSettings(IsolatedStorageFile storageFile)
        {
            container = storageFile;

            if (!storageFile.FileExists(localSettingsFileName))
            {
                settings = new Dictionary <string, object>();
                return;
            }

            using (var fileStream = storageFile.OpenFile(localSettingsFileName, FileMode.Open))
            {
                try
                {
                    var serializer = Dependency.Resolve <IBinarySerializer, BinarySerializer>();
                    settings = serializer.Deserialize <Dictionary <string, object> >((Stream)fileStream);
                }
                catch (Exception ex)
                {
                    var exceptionHandler = Dependency.Resolve <IExceptionHandler>();
                    if (exceptionHandler.ShouldRethrowException(ex, this))
                    {
                        throw;
                    }

                    settings = new Dictionary <string, object>();
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            //get store
            store = IsolatedStorageFile.GetUserStoreForApplication();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
        }
 public IsolatedStorageFileStorage()
 {
     __IsoStorage =
         IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly,
                                      null,
                                      null);
 }
Esempio n. 5
0
		public override void Setup()
		{
			base.Setup ();
			Device.PlatformServices = new MockPlatformServices (getStreamAsync: GetStreamAsync);
			NativeStore = IsolatedStorageFile.GetUserStoreForAssembly ();
			networkcalls = 0;
		}
Esempio n. 6
0
 private static void GetFile(IsolatedStorageFile istorage, string filename, Action<File> returns)
 {
     using (var openedFile = istorage.OpenFile(filename, System.IO.FileMode.Open))
     {
         ReadFileFromOpenFile(filename, openedFile, returns);
     }
 }
Esempio n. 7
0
		/////////////////////////////////////////////////////////////////////////////
		public DocumentIO()
		{
			m_file = null;
			m_stream = null;
			m_writer = null;
			m_reader = null;
		}
Esempio n. 8
0
 // Code to execute when the application is closing (eg, user hit Back)
 // This code will not execute when the application is deactivated
 private void Application_Closing(object sender, ClosingEventArgs e)
 {
     System.IO.IsolatedStorage.IsolatedStorageFile iso = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
     System.Xml.Serialization.XmlSerializer        xs  = new System.Xml.Serialization.XmlSerializer(typeof(AccountDB));
     System.IO.StreamWriter sw = new System.IO.StreamWriter(iso.OpenFile("AccountArchive.xml", System.IO.FileMode.OpenOrCreate));
     xs.Serialize(sw, this.WorkingDB);
 }
Esempio n. 9
0
 public IsolatedStorageTracer()
 {
     _storageFile = IsolatedStorageFile.GetUserStoreForApplication();
     _storageFileStream = _storageFile.OpenFile("MagellanTrace.log", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     _streamWriter = new StreamWriter(_storageFileStream);
     _streamWriter.AutoFlush = true;
 }
 internal AssemblyResourceStore(Type evidence)
 {
     this.evidence = evidence;
     logger = Initializer.Instance.WindsorContainer.Resolve<ILoggingService>();
     _isoFile = IsolatedStorageFile.GetMachineStoreForAssembly();
     _backingFile = new IsolatedStorageFileStream(evidence.Assembly.GetName().Name, FileMode.OpenOrCreate, _isoFile);
     if (_backingFile.Length > 0)
     {
         try
         {
             var formatter = new BinaryFormatter();
             store = (Dictionary<string, object>)formatter.Deserialize(_backingFile);
         }
         catch (Exception ex)
         {
             logger.Log(Common.LogLevel.Error, string.Format("Error deserializing resource store for {0}. Resetting resource store.", evidence.Assembly.GetName().Name));
             logger.Log(Common.LogLevel.Debug, string.Format("Deserialize error: {0}", ex.Message));
             store = new Dictionary<string, object>();
         }
     }
     else
     {
         store = new Dictionary<string, object>();
     }
 }
        public IsolatedStorageDirectory(string dirName)
        {
            _is = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForAssembly();

            _dirName = dirName;
            _is.CreateDirectory(dirName);
        }
Esempio n. 12
0
        public void LoadSettings()
        {
            // Look for settings in isolated storage
            this.isoStore = IsolatedStorageFile.GetUserStoreForAssembly();

            //this.isoStore.DeleteFile("Prefs.txt");

            string[] files = this.isoStore.GetFileNames(prefsFilename);

            if (files.Length > 0)
            {
                using (StreamReader reader = new StreamReader(new IsolatedStorageFileStream(prefsFilename, FileMode.Open, this.isoStore)))
                {
                    // Decrypt the stream
                    string decrypted = Encryption.Decrypt(reader.ReadToEnd(), key, false);
                    StringReader sr = new StringReader(decrypted);

                    // Deserialize the settings
                    XmlSerializer serializer = new XmlSerializer(this.GetType());
                    BackupSettings settings = (BackupSettings)serializer.Deserialize(sr);

                    // Set properties
                    this.ServerUrl = settings.ServerUrl;
                    this.AuthenticationKey = settings.AuthenticationKey;
                    this.CertificateIdentity = settings.CertificateIdentity;
                    this.StorageAccounts = settings.StorageAccounts;
                }
            }
        }
Esempio n. 13
0
        public Accelerometro()
        {
            InitializeComponent();

            accelerometer = new Accelerometer();
            accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(100);
            accelerometer.Start();

            myFile = IsolatedStorageFile.GetUserStoreForApplication();

            if (!myFile.FileExists("Impo.txt"))
            {
                IsolatedStorageFileStream dataFile = myFile.CreateFile("Impo.txt");
                dataFile.Close();
            }

            Wb = new WebBrowser();
            Connesso = false;
            Carica();

            System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
            dt.Interval = new TimeSpan(0, 0, 0, 0, 250); // 500 Milliseconds
            dt.Tick += new EventHandler(dt_Tick);
            dt.Start();
        }
Esempio n. 14
0
        /// <summary>
        /// 构建分片上传对象
        /// </summary>
        /// <param name="httpManager">HttpManager对象</param>
        /// <param name="recorder">分片上传进度记录器</param>
        /// <param name="recordKey">分片上传进度记录文件名</param>
        /// <param name="filePath">上传的沙盒文件全路径</param>
        /// <param name="key">保存在七牛的文件名</param>
        /// <param name="token">上传凭证</param>
        /// <param name="uploadOptions">上传可选设置</param>
        /// <param name="upCompletionHandler">上传完成结果处理器</param>
        public ResumeUploader(HttpManager httpManager, ResumeRecorder recorder, string recordKey, string filePath,
            string key, string token, UploadOptions uploadOptions, UpCompletionHandler upCompletionHandler)
        {
            this.httpManager = httpManager;
            this.resumeRecorder = recorder;
            this.recordKey = recordKey;
            this.filePath = filePath;
            this.key = key;
            this.storage = IsolatedStorageFile.GetUserStoreForApplication();
            this.uploadOptions = (uploadOptions == null) ? UploadOptions.defaultOptions() : uploadOptions;
            this.upCompletionHandler = new UpCompletionHandler(delegate(string fileKey, ResponseInfo respInfo, string response)
            {
                uploadOptions.ProgressHandler(key, 1.0);

                if (this.fileStream != null)
                {
                    try
                    {
                        this.fileStream.Close();
                    }
                    catch (Exception) { }
                }

                if (upCompletionHandler != null)
                {
                    upCompletionHandler(key, respInfo, response);
                }
            });
            this.httpManager.setAuthHeader("UpToken " + token);
            this.chunkBuffer = new byte[Config.CHUNK_SIZE];
        }
        /************************************* Public implementations *******************************/
        public PodcastSubscriptionModel()
        {
            m_podcastEpisodesManager = new PodcastEpisodesManager(this);
            m_isolatedFileStorage = IsolatedStorageFile.GetUserStoreForApplication();

            createLogoCacheDirs();
        }
Esempio n. 16
0
 public virtual void SaveToFile(string fileName)
 {
     System.IO.StreamWriter streamWriter = null;
     System.IO.IsolatedStorage.IsolatedStorageFile       isoFile   = null;
     System.IO.IsolatedStorage.IsolatedStorageFileStream isoStream = null;
     try
     {
         isoFile      = IsolatedStorageFile.GetUserStoreForApplication();
         isoStream    = new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileName, FileMode.Create, isoFile);
         streamWriter = new System.IO.StreamWriter(isoStream);
         string             xmlString = Serialize();
         System.IO.FileInfo xmlFile   = new System.IO.FileInfo(fileName);
         streamWriter = xmlFile.CreateText();
         streamWriter.WriteLine(xmlString);
         streamWriter.Close();
         isoStream.Close();
     }
     finally
     {
         if ((streamWriter != null))
         {
             streamWriter.Dispose();
         }
         if ((isoFile != null))
         {
             isoFile.Dispose();
         }
         if ((isoStream != null))
         {
             isoStream.Dispose();
         }
     }
 }
Esempio n. 17
0
        private void showImage()
        {
            if (App.ViewModel.forShare != null)
            {
                imagePicker.Content = App.ViewModel.forShare.ItemName;
                imagePicker.Opacity = 0.5;
                System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                //点击超链接后图片存在
                if (isf.FileExists(App.ViewModel.forShare.ItemName + ".jpg"))
                {
                    isf.CopyFile(App.ViewModel.forShare.ItemName + ".jpg", "abc.jpg", true);
                    System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.OpenFile("abc.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    System.Windows.Media.Imaging.BitmapImage            bmp1        = new System.Windows.Media.Imaging.BitmapImage();
                    bmp1.SetSource(PhotoStream); //把文件流转换为图片
                    PhotoStream.Close();         //读取完毕,关闭文件流

                    System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush();
                    ib.ImageSource = bmp1;
                    tip.Background = ib;      //把图片设置为控件的背景图
                    //imageTip.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            //如果存在背景,则显示关联按钮
            if (tip.Background != null)
            {
                appBar3();
            }
        }
Esempio n. 18
0
        public override void Dispose()
        {
            if (Store != null)
                Store.Dispose();

            Store = null;
        }
 public TextToSpeech(DictionaryRecord r) : base()
 {
     FrameworkDispatcher.Update(); // initialize XNA (required)
     SpeakCompleted += new EventHandler<BingTranslator.SpeakCompletedEventArgs>(TextToSpeech_SpeakCompleted);
     store = IsolatedStorageFile.GetUserStoreForApplication();
     record = r;
 }
        // Method to retrieve all directories, recursively, within a store.
        public static List<String> GetAllDirectories(string pattern, IsolatedStorageFile storeFile)
        {
            // Get the root of the search string.
            string root = Path.GetDirectoryName(pattern);

            if (root != "")
            {
                root += "/";
            }

            // Retrieve directories.
            List<String> directoryList = new List<String>(storeFile.GetDirectoryNames(pattern));

            // Retrieve subdirectories of matches.
            for (int i = 0, max = directoryList.Count; i < max; i++)
            {
                string directory = directoryList[i] + "/";
                List<String> more = GetAllDirectories(root + directory + "*", storeFile);

                // For each subdirectory found, add in the base path.
                for (int j = 0; j < more.Count; 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.Count;
                max += more.Count;
            }

            return directoryList;
        }
Esempio n. 21
0
 /// <summary>
 /// Create a Note instance and create a note file.
 /// </summary>
 /// <param name="title"></param>
 /// <param name="body"></param>
 /// <param name="iStorage"></param>
 /// <param name="dateTime"></param>
 public Note(string title, DateTime dateTime, string body, IsolatedStorageFile iStorage)
 {
     Title = title;
     DateTime = dateTime;
     Body = body;
     SaveFromTitle(iStorage);
 }
        /// <summary>
        /// Collects the Paths of Directories and Files inside a given Directory relative to it.
        /// </summary>
        /// <param name="Iso">The Isolated Storage to Use</param>
        /// <param name="directory">The Directory to crawl</param>
        /// <param name="relativeSubDirectories">relative Paths to the subdirectories in the given directory, ordered top - down</param>
        /// <param name="relativeSubFiles">relative Paths to the files in the given directory and its children, ordered top - down</param>
        private static void CollectSubdirectoriesAndFilesBreadthFirst(IsolatedStorageFile Iso, string directory, out IList<string> relativeSubDirectories, out IList<string> relativeSubFiles)
        {
            var relativeDirs = new List<string>();
            var relativeFiles = new List<string>();
            var toDo = new Queue<string>();

            toDo.Enqueue(string.Empty);

            while (toDo.Count > 0)
            {
                var relativeSubDir = toDo.Dequeue();
                var absoluteSubDir = Path.Combine(directory, relativeSubDir);
                var queryString = string.Format("{0}\\*", absoluteSubDir);

                foreach (var file in Iso.GetFileNames(queryString))
                {
                    relativeFiles.Add(Path.Combine(relativeSubDir, file));
                }

                foreach (var dir in Iso.GetDirectoryNames(queryString))
                {
                    var relativeSubSubdir = Path.Combine(relativeSubDir, dir);
                    toDo.Enqueue(relativeSubSubdir);
                    relativeDirs.Add(relativeSubSubdir);
                }
            }

            relativeSubDirectories = relativeDirs;
            relativeSubFiles = relativeFiles;
        }
Esempio n. 23
0
 public static T LoadFromFile(string fileName)
 {
     System.IO.IsolatedStorage.IsolatedStorageFile       isoFile   = null;
     System.IO.IsolatedStorage.IsolatedStorageFileStream isoStream = null;
     System.IO.StreamReader sr = null;
     try
     {
         isoFile   = IsolatedStorageFile.GetUserStoreForApplication();
         isoStream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileName, FileMode.Open, isoFile);
         sr        = new System.IO.StreamReader(isoStream);
         string xmlString = sr.ReadToEnd();
         isoStream.Close();
         sr.Close();
         return(Deserialize(xmlString));
     }
     finally
     {
         if ((isoFile != null))
         {
             isoFile.Dispose();
         }
         if ((isoStream != null))
         {
             isoStream.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
        protected BaseStorageCache(IsolatedStorageFile isf, string cacheDirectory, ICacheFileNameGenerator cacheFileNameGenerator, long cacheMaxLifetimeInMillis = DefaultCacheMaxLifetimeInMillis)
        {
            if (isf == null)
            {
                throw new ArgumentNullException("isf");
            }

            if (String.IsNullOrEmpty(cacheDirectory))
            {
                throw new ArgumentException("cacheDirectory name could not be null or empty");
            }

            if (!cacheDirectory.StartsWith("\\"))
            {
                throw new ArgumentException("cacheDirectory name should starts with double slashes: \\");
            }

            if (cacheFileNameGenerator == null)
            {
                throw new ArgumentNullException("cacheFileNameGenerator");
            }

            ISF = isf;
            CacheDirectory = cacheDirectory;
            CacheFileNameGenerator = cacheFileNameGenerator;
            CacheMaxLifetimeInMillis = cacheMaxLifetimeInMillis;

            // Creating cache directory if it not exists
            ISF.CreateDirectory(CacheDirectory);
        }
Esempio n. 25
0
        //*******************************************************************************************
        //Enable this if you'd like to be able access the list from outside the class. All list
        //methods are commented out below and replaced with Debug.WriteLine.
        //Default implementation is to simply output the directories to the console (Debug.WriteLine)
        //so if it looks like nothing's happening, check the Output window :) - keyboardP
        // public static List<string> listDir = new List<string>();
        //********************************************************************************************
        //Use "*" as the pattern string in order to retrieve all files and directories
        public static void GetIsolatedStorageView(string pattern, IsolatedStorageFile storeFile)
        {
            string root = System.IO.Path.GetDirectoryName(pattern);

            if (root != "")
            {
                root += "/";
            }

            string[] directories = storeFile.GetDirectoryNames(pattern);
            //if the root directory has not FOLDERS, then the GetFiles() method won't be called.
            //the line below calls the GetFiles() method in this event so files are displayed
            //even if there are no folders
            //if (directories.Length == 0)
                GetFiles(root, "*", storeFile);

            for (int i = 0; i < directories.Length; i++)
            {
                string dir = directories[i] + "/";

                //Add this directory into the list
                // listDir.Add(root + directories[i]);

                //Write to output window
                Debug.WriteLine(root + directories[i]);

                //Get all the files from this directory
                GetFiles(root + directories[i], pattern, storeFile);

                //Continue to get the next directory
                GetIsolatedStorageView(root + dir + "*", storeFile);
            }
        }
Esempio n. 26
0
        public static bool FileIsExpired(IsolatedStorageFile isolatedStorage, string imageFileName, int cacheDays)
        {
            // Very very very ugly function to determine lastwritetime of file in isolated storage
            if (cacheDays == 0)
                return false;

            try
            {
                var propertyInfo = isolatedStorage.GetType().GetField("m_RootDir",
                                                                      BindingFlags.NonPublic | BindingFlags.Instance);
                if (propertyInfo != null)
                {
                    var rootDir = propertyInfo.GetValue(isolatedStorage) as string;
                    if (rootDir != null)
                    {
                        var file = new FileInfo(rootDir + imageFileName);
                        if (file.Exists)
                        {
                            if (file.LastWriteTime < DateTime.Now.AddDays(-cacheDays))
                                return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
            return false;
        }
Esempio n. 27
0
        private static void GetFiles(string dir, string pattern, IsolatedStorageFile storeFile)
        {
            string fileString = System.IO.Path.GetFileName(pattern);

            string[] files = storeFile.GetFileNames(pattern);

            try
            {
                for (int i = 0; i < storeFile.GetFileNames(dir + "/" + fileString).Length; i++)
                {

                    //Files are prefixed with "--"

                    //Add to the list
                    //listDir.Add("--" + dir + "/" + storeFile.GetFileNames(dir + "/" + fileString)[i]);

                    Debug.WriteLine("--" + dir + "/" + storeFile.GetFileNames(dir + "/" + fileString)[i]);
                }
            }
            catch (IsolatedStorageException ise)
            {
                Debug.WriteLine("An IsolatedStorageException exception has occurred: " + ise.InnerException);
            }
            catch (Exception e)
            {
                Debug.WriteLine("An exception has occurred: " + e.InnerException);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// 申请500M的存储空间
        /// </summary>
        /// <returns></returns>
        public static bool IncreaseQuotaTo()
        {
            //如果本函数代码断点调试将不能正常执行。申请缓存对话框将不能阻塞。
            long StorageSpace          = 200 * 1024 * 1024; //申请空间大小
            long IncreaseSpace         = 100 * 1024 * 1024; //增量空间
            long MinAvailableFreeSpace = 10 * 1024 * 1024;  //最小可用空间

            try
            {
                lock (lockStorageObject)
                {
                    using (System.IO.IsolatedStorage.IsolatedStorageFile file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForSite())
                    {
                        if (file.Quota < StorageSpace)
                        {
                            return(file.IncreaseQuotaTo(StorageSpace));
                        }
                        else if (file.AvailableFreeSpace < MinAvailableFreeSpace)
                        {
                            return(file.IncreaseQuotaTo(file.Quota + IncreaseSpace));
                        }
                    }
                }
                return(true);
            }
            catch (System.IO.IsolatedStorage.IsolatedStorageException)
            {
                return(false);
            }
        }
Esempio n. 29
0
        // Constructor
        public MainPage()
        {
            this._WatchlistFile = IsolatedStorageFile.GetUserStoreForApplication();
            this._WatchlistFileName = "Watchlist.txt";

            // If the file doesn't exist we need to create it so the user has it for us to reference.
            if (!this._WatchlistFile.FileExists(this._WatchlistFileName))
            {
                this._WatchlistFile.CreateFile(this._WatchlistFileName).Close();
            }

            this._WatchList = this._ReadWatchlistFile();

            InitializeComponent();

            // Init WebClient's and set callbacks
            this._LookupWebClient = new WebClient();
            this._LookupWebClient.OpenReadCompleted += new OpenReadCompletedEventHandler(this.LookupSymbolComplete);

            this._NewsWebClient = new WebClient();
            this._NewsWebClient.OpenReadCompleted += new OpenReadCompletedEventHandler(this.NewsSearchComplete);

            this._QuoteWebClient = new WebClient();
            this._QuoteWebClient.OpenReadCompleted += new OpenReadCompletedEventHandler(this.GetQuoteComplete);

            this.SymbolTextBox.Text = _DefaultInputText;
        }
Esempio n. 30
0
 public ReferenceBuilder_with_modules()
 {
     storage = IsolatedStorageFile.GetUserStoreForDomain();
     // 'b/4.js' <- 'a/1.js' <- 'a/3.js' <- 'b/2.js'
     builder = new ReferenceBuilder(
         new ModuleContainer(new[]
         {
             new Module(
                 "a",
                 new[]
                 {
                     CreateScript("1", "a", "b/4.js"),
                     CreateScript("2", "a", "a/3.js"),
                     CreateScript("3", "a", "a/1.js")
                 },
                 new [] { "b" },
                 null
             ),
             new Module(
                 "b",
                 new[]
                 {
                     CreateScript("4", "b")
                 },
                 new string[0],
                 null
             )
         }, storage, tw => null)
     );
 }
        /// <summary>
        /// Imports a CartridgeSavegame from metadata associated to a savegame
        /// file.
        /// </summary>
        /// <param name="gwsFilePath">Path to the GWS savegame file.</param>
        /// <param name="isf">Isostore file to use to load.</param>
        /// <returns>The cartridge savegame.</returns>
        /// 
        public static CartridgeSavegame FromCache(string gwsFilePath, IsolatedStorageFile isf)
        {
            // Checks that the metadata file exists.
            string mdFile = gwsFilePath + ".mf";
            if (!(isf.FileExists(mdFile)))
            {
                throw new System.IO.FileNotFoundException(mdFile + " does not exist.");
            }
            
            // Creates a serializer.
            DataContractSerializer serializer = new DataContractSerializer(typeof(CartridgeSavegame));

            // Reads the object.
            CartridgeSavegame cs;
            using (IsolatedStorageFileStream fs = isf.OpenFile(mdFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                // Reads the object.
                object o = serializer.ReadObject(fs);

                // Casts it.
                cs = (CartridgeSavegame)o;
            }

            // Adds non-serialized content.
            cs.SavegameFile = gwsFilePath;
            cs.MetadataFile = mdFile;

            // Returns it.
            return cs;
        }
Esempio n. 32
0
 public SetupApplicationViewModel(IGlobalSettingsService globalSettingsService)
 {
     _storage = IsolatedStorageFile.GetUserStoreForApplication();
     CacheModules = globalSettingsService.IsCachingEnabled;
     Quota = _storage.Quota / 1048576;
     _globalSettingsService = globalSettingsService;
 }
	public IsolatedStorageFileStream(String path, FileMode mode,
									 FileAccess access, FileShare share,
									 IsolatedStorageFile sf)
			: this(path, mode, access, share, BUFSIZ, sf)
			{
				// Nothing to do here.
			}
Esempio n. 34
0
 private static void VerifyFolderExistsAsync(IsolatedStorageFile isolatedStorageFile)
 {
     if (!isolatedStorageFile.DirectoryExists(MonthFolder))
     {
         isolatedStorageFile.CreateDirectory(MonthFolder);
     }
 }
Esempio n. 35
0
 /// <summary>
 /// 读取本地文件信息,SilverLight缓存中
 /// </summary>
 /// <param name="rFileName">存储文件名</param>
 /// <returns>返回文件数据</returns>
 public static byte[] ReadSlByteFile(string rFileName)
 {
     System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
     System.IO.Stream stream = null;
     byte[]           buffer = null;
     try
     {
         isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
         if (!isf.FileExists(rFileName))
         {
             return(null);
         }
         stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, isf);
         buffer = new byte[stream.Length];
         stream.Read(buffer, 0, (int)stream.Length);
     }
     finally
     {
         if (stream != null)
         {
             stream.Close(); // Close the stream
             stream.Dispose();
         }
         isf.Dispose();
     }
     return(buffer);
 }
Esempio n. 36
0
		private static string CreateIsolatedPath (IsolatedStorageFile isf, string path, FileMode mode)
		{
			if (path == null)
				throw new ArgumentNullException ("path");

			if (!Enum.IsDefined (typeof (FileMode), mode))
				throw new ArgumentException ("mode");

			if (isf == null) {
				// we can't call GetUserStoreForDomain here because it depends on 
				// Assembly.GetCallingAssembly (), which would be our constructor,
				// i.e. the result would always be mscorlib.dll. So we need to do 
				// a small stack walk to find who's calling the constructor

				isf = IsolatedStorageFile.GetStore (IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly,
#if MOBILE
					null, null);
#else
					IsolatedStorageFile.GetDomainIdentityFromEvidence (AppDomain.CurrentDomain.Evidence), 
					IsolatedStorageFile.GetAssemblyIdentityFromEvidence (new StackFrame (3).GetMethod ().ReflectedType.Assembly.UnprotectedGetEvidence ())); // skip self and constructor
#endif
			}

			if (isf.IsDisposed)
				throw new ObjectDisposedException ("IsolatedStorageFile");
			if (isf.IsClosed)
				throw new InvalidOperationException ("Storage needs to be open for this operation.");

			// ensure that the _root_ isolated storage can be (and is) created.
			FileInfo fi = new FileInfo (isf.Root);
			if (!fi.Directory.Exists)
				fi.Directory.Create ();

			// remove the root path character(s) if they exist
			if (Path.IsPathRooted (path)) {
				string root = Path.GetPathRoot (path);
				path = path.Remove (0, root.Length);
			}

			// other directories (provided by 'path') must already exists
			string file = Path.Combine (isf.Root, path);

			string full = Path.GetFullPath (file);
			full = Path.GetFullPath (file);
			if (!full.StartsWith (isf.Root))
				throw new IsolatedStorageException ();

			fi = new FileInfo (file);
			if (!fi.Directory.Exists) {
				// don't leak the path information for isolated storage
				string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
				throw new DirectoryNotFoundException (String.Format (msg, path));
			}

			// FIXME: this is probably a good place to Assert our security
			// needs (once Mono supports imperative security stack modifiers)

			return file;
		}
 // On NetFX FileStream has an internal no arg constructor that we utilize to provide the facade. We don't have access
 // to internals in CoreFX so we'll do the next best thing and contort ourselves into the SafeFileHandle constructor.
 // (A path constructor would try and create the requested file and give us two open handles.)
 //
 // We only expose our own nested FileStream so the base class having a handle doesn't matter. Passing a new SafeFileHandle
 // with ownsHandle: false avoids the parent class closing without our knowledge.
 private IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, InitialiationData initializationData)
     : base(new SafeFileHandle(initializationData.NestedStream.SafeFileHandle.DangerousGetHandle(), ownsHandle: false), access, bufferSize)
 {
     _isf = initializationData.StorageFile;
     _givenPath = path;
     _fullPath = initializationData.FullPath;
     _fs = initializationData.NestedStream;
 }
Esempio n. 38
0
        public static string[] GetFilesName(string path)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            string searchpath = System.IO.Path.Combine(path, "*.*");

            string[] filesInSubDirs = isf.GetFileNames(searchpath);
            return(filesInSubDirs);
        }
Esempio n. 39
0
        public Stream Open(FileMode mode, FileAccess access, FileShare fileShare)
        {
#if NET35
            return(new IsolatedStorageFileStream(systemFilename, mode, access, fileShare, Storage));
#else
            return(Storage.OpenFile(systemFilename, mode, access, fileShare));
#endif
        }
Esempio n. 40
0
        public static void CreateDirectory(string path)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();



            if (isf.DirectoryExists(path))
            {
                isf.CreateDirectory(path);
            }
        }
Esempio n. 41
0
        private void SaveSettings()
        {
            string connectionHistoryFile = this.GetConnectionHistoryFile();

            Log.WriteLine("SaveSettings");
            Log.Indent();
            DatabaseManager.DatabaseType databaseType = (DatabaseManager.CurrentDatabaseType == DatabaseManager.DatabaseType.Invalid) ? DatabaseManager.lastDatabaseType : DatabaseManager.CurrentDatabaseType;
            Log.WriteLine("#Last Database type: " + databaseType);
            foreach (System.Collections.Generic.KeyValuePair <DatabaseManager.DatabaseType, System.Collections.Generic.List <string> > current in DatabaseManager.m_LastConnection)
            {
                foreach (string current2 in current.Value)
                {
                    Log.WriteLine("{0},{1}", new object[]
                    {
                        current.Key,
                        current2
                    });
                }
            }
            Log.Unindent();
            System.IO.StreamWriter streamWriter = null;
            try
            {
                if (Command.ConfigFile.Debug)
                {
                    streamWriter = new System.IO.StreamWriter(connectionHistoryFile, false);
                }
                else
                {
                    System.IO.IsolatedStorage.IsolatedStorageFile store = System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(System.IO.IsolatedStorage.IsolatedStorageScope.User | System.IO.IsolatedStorage.IsolatedStorageScope.Assembly, null, null);
                    streamWriter = new System.IO.StreamWriter(new System.IO.IsolatedStorage.IsolatedStorageFileStream(System.IO.Path.GetFileName(connectionHistoryFile), System.IO.FileMode.Create, store));
                }
                streamWriter.WriteLine("#Last Database type: " + databaseType);
                foreach (System.Collections.Generic.KeyValuePair <DatabaseManager.DatabaseType, System.Collections.Generic.List <string> > current3 in DatabaseManager.m_LastConnection)
                {
                    foreach (string current4 in current3.Value)
                    {
                        streamWriter.WriteLine("{0},{1}", current3.Key, current4);
                    }
                }
            }
            catch
            {
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                }
            }
        }
 private static void SaveKeyToFile(string fileName, string key)
 {
     using (System.IO.IsolatedStorage.IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null))
     {
         using (var oStream = new IsolatedStorageFileStream(fileName, FileMode.Create, isoStore))
         {
             using (var writer = new StreamWriter(oStream))
             {
                 writer.WriteLine(key);
             }
         }
     }
 }
Esempio n. 43
0
 internal static void ClearSlFiles(string rFileName)
 {
     System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
     if (rFileName == null || rFileName.TrimEnd() == "")
     {
         isf.Remove();
     }
     else
     {
         if (isf.FileExists(rFileName))
         {
             isf.DeleteFile(rFileName);
         }
     }
     isf.Dispose();
 }
Esempio n. 44
0
        public string Read(string filename)
        {
            string result = string.Empty;

            System.IO.IsolatedStorage.IsolatedStorageFile isoStore =
                System.IO.IsolatedStorage.IsolatedStorageFile.
                GetUserStoreForDomain();
            try
            {
                // Checks to see if the options.txt file exists.
                if (isoStore.GetFileNames(filename).GetLength(0) != 0)
                {
                    // Opens the file because it exists.
                    System.IO.IsolatedStorage.IsolatedStorageFileStream isos =
                        new System.IO.IsolatedStorage.IsolatedStorageFileStream
                            (filename, System.IO.FileMode.Open, isoStore);
                    System.IO.StreamReader reader = null;
                    try
                    {
                        reader = new System.IO.StreamReader(isos);

                        // Reads the values stored.
                        result = reader.ReadLine();
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine
                            ("Cannot read options " + ex.ToString());
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine
                    ("Cannot read options " + ex.ToString());
            }
            return(result);
        }
Esempio n. 45
0
 private void Picture_Save(object sender, EventArgs e)
 {
     System.IO.IsolatedStorage.IsolatedStorageFile isf2 = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
     //  if (isf2.FileExists(imagePicker.Content + ".jpg")) isf2.DeleteFile(imagePicker.Content + ".jpg");
     if (isf2.FileExists("abc.jpg"))
     {
         isf2.CopyFile("abc.jpg", imagePicker.Content + ".jpg", true);
         //MessageBox.Show("关联成功");
         //takePhote();
         if (MessageBox.Show(txtnote.Resources.StringLibrary.chenggong + "!", txtnote.Resources.StringLibrary.guanlian, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
         {
             MainPano.DefaultItem = ViewPano;
             imageTip.Visibility  = System.Windows.Visibility.Visible;
         }
     }
     else
     {
         MessageBox.Show("Fail!");
     }
 }
Esempio n. 46
0
        /// <summary>
        /// Loads local audio information.
        /// </summary>
        public void ReadAudioFileInfo()
        {
            AudioFiles.Clear();

            // Load the image which was filtered from isolated app storage.
            System.IO.IsolatedStorage.IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();

            try
            {
                string[] fileNames = myStore.GetFileNames();
                foreach (string s in fileNames)
                {
                    AudioFileModel audioFile = new AudioFileModel();
                    audioFile.FileName = s;
                    IsolatedStorageFileStream fileStream = myStore.OpenFile(s, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    audioFile.FileSize = "" + fileStream.Length + " bytes";

                    // Read sample rate and channel count
                    Encoding encoding = Encoding.UTF8;
                    byte[]   bytes    = new byte[4];

                    // channel count
                    fileStream.Seek(22, SeekOrigin.Begin);
                    fileStream.Read(bytes, 0, 2);
                    audioFile.ChannelCount = BitConverter.ToInt16(bytes, 0);

                    // sample rate
                    fileStream.Read(bytes, 0, 4);
                    audioFile.SampleRate = BitConverter.ToInt32(bytes, 0);

                    audioFile.FileLength = "" + fileStream.Length / (2 * audioFile.SampleRate * audioFile.ChannelCount) + " seconds";
                    AudioFiles.Add(audioFile);

                    fileStream.Dispose();
                }
            }
            catch
            {
                MessageBox.Show("Error while trying to read audio files.");
            }
        }
Esempio n. 47
0
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            MenuItem clickedLink = (MenuItem)sender;

            if (clickedLink != null)
            {
                ToDoItem toDoForDelete = clickedLink.DataContext as ToDoItem;
                fileName = toDoForDelete.ItemName;
                //删除图片
                System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                if (isf.FileExists(toDoForDelete.ItemName + ".jpg"))
                {
                    isf.DeleteFile(toDoForDelete.ItemName + ".jpg");
                }
                //删除磁贴
                deleteTile();
                //  删除数据
                App.ViewModel.DeleteToDoItem(toDoForDelete);
            }
            this.Focus();
        }
Esempio n. 48
0
        // Writes the button options to the isolated storage.
        public void Write(string filename, string content)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isoStore =
                System.IO.IsolatedStorage.IsolatedStorageFile.
                GetUserStoreForDomain();
            try
            {
                // Checks if the file exists and, if it does, tries to delete it.
                if (isoStore.GetFileNames(filename).GetLength(0) != 0)
                {
                    isoStore.DeleteFile(filename);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine
                    ("Cannot delete file " + ex.ToString());
            }

            // Creates the options file and writes the button options to it.
            System.IO.StreamWriter writer = null;
            try
            {
                System.IO.IsolatedStorage.IsolatedStorageFileStream isos = new
                                                                           System.IO.IsolatedStorage.IsolatedStorageFileStream(filename,
                                                                                                                               System.IO.FileMode.CreateNew, isoStore);

                writer = new System.IO.StreamWriter(isos);
                writer.WriteLine(content);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine
                    ("Cannot write options " + ex.ToString());
            }
            finally
            {
                writer.Close();
            }
        }
Esempio n. 49
0
        private void showBackground()
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            //点击超链接后图片存在

            if (isf.FileExists("back_temp.jpg"))
            {
                System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.OpenFile("back_temp.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.Windows.Media.Imaging.BitmapImage            bmp1        = new System.Windows.Media.Imaging.BitmapImage();
                bmp1.SetSource(PhotoStream); //把文件流转换为图片
                PhotoStream.Close();         //读取完毕,关闭文件流

                System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush();
                ib.ImageSource      = bmp1;
                MainPano.Background = ib;  //把图片设置为控件的背景图
                //imageTip.Visibility = System.Windows.Visibility.Collapsed;
            }
            // else
            //  {
            //     MainPano.Background = null;
            //  }
        }
Esempio n. 50
0
 /// <summary>
 /// 读取本地文件信息,SilverLight缓存中
 /// </summary>
 /// <param name="rFileName">存储文件名</param>
 /// <returns>返回消息文本</returns>
 public static string ReadSlTextFile(string rFileName)
 {
     System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
     System.IO.Stream     stream = null;
     System.IO.TextReader reader = null;
     try
     {
         isf    = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
         stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, isf);
         reader = new System.IO.StreamReader(stream);
         string sLine = reader.ReadToEnd();
         //string sLine=reader.ReadLine();
         return(sLine);
     }
     catch
     {
         return(string.Empty);
     }
     finally
     {
         try
         {
             if (reader != null)
             {
                 reader.Close(); // Close the reader
             }
             if (reader != null)
             {
                 stream.Close();
             }// Close the stream
             isf.Dispose();
         }
         catch
         {
         }
     }
 }
Esempio n. 51
0
        /// <summary>
        /// 保存信息至本地文件,SilverLight缓存中
        /// </summary>
        /// <param name="rFileName">存储文件名</param>
        /// <param name="rText">消息文本</param>
        public static void WriteSlTextFile(string rFileName, string rText)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
            System.IO.Stream     stream = null;
            System.IO.TextWriter writer = null;
            try
            {
                isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                if (rFileName.IndexOf(':') >= 0)
                {
                    rFileName = rFileName.Substring(rFileName.LastIndexOf(':') + 1);
                }
                string rPath = System.IO.Path.GetDirectoryName(rFileName);
                if (isf.DirectoryExists(rPath) == false)
                {
                    isf.CreateDirectory(rPath);
                }
                stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, isf);
                //stream.Seek(0, System.IO.SeekOrigin.End);
                writer = new System.IO.StreamWriter(stream);
                writer.Write(rText);

                writer.Flush();
            }
            finally
            {
                try
                {
                    writer.Close();
                    stream.Close();
                    isf.Dispose();
                }
                catch
                {
                }
            }
        }
Esempio n. 52
0
        void PhotoTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
            {
                System.Windows.Media.Imaging.WriteableBitmap  bmp = Microsoft.Phone.PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                if (isf.FileExists("abc.jpg"))
                {
                    isf.DeleteFile("abc.jpg");
                }
                System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.CreateFile("abc.jpg");
                System.Windows.Media.Imaging.Extensions.SaveJpeg(bmp, PhotoStream, 432, 645, 0, 100);      //这里设置保存后图片的大小、品质
                PhotoStream.Close();                                                                       //写入完毕,关闭文件流

                PhotoStream = isf.OpenFile("abc.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read); //读取刚刚保存的图片的文件流
                System.Windows.Media.Imaging.BitmapImage bmp1 = new System.Windows.Media.Imaging.BitmapImage();
                bmp1.SetSource(PhotoStream);                                                               //把文件流转换为图片
                PhotoStream.Close();                                                                       //读取完毕,关闭文件流

                System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush();
                ib.ImageSource      = bmp1;
                tip.Background      = ib;//把图片设置为控件的背景图
                imageTip.Visibility = System.Windows.Visibility.Collapsed;
                if (imagePicker.Content.ToString() == txtnote.Resources.StringLibrary.imagename)
                {
                    if (MessageBox.Show(txtnote.Resources.StringLibrary.imagename, txtnote.Resources.StringLibrary.guanlian, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        NavigationService.Navigate(new Uri("/txtnote;component/Pick.xaml", UriKind.Relative));
                    }
                }
                else
                {
                    appBar3();
                }
            }
        }
Esempio n. 53
0
        /// <summary>
        /// 保存信息至本地文件,SilverLight缓存中
        /// </summary>
        /// <param name="rFileName"></param>
        /// <param name="buffer"></param>
        public static void WriteSlByteFile(string rFileName, byte[] buffer)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
            System.IO.Stream stream = null;
            try
            {
                isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

                if (rFileName.IndexOf(':') >= 0)
                {
                    rFileName = rFileName.Substring(rFileName.LastIndexOf(':') + 1);
                }
                ClearSlFile(rFileName);
                string rPath = System.IO.Path.GetDirectoryName(rFileName);
                if (rPath != "")
                {
                    isf.CreateDirectory(rPath);
                }

                stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Write, isf);
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();
            }
            finally
            {
                try
                {
                    stream.Close(); // Close the stream too
                    stream.Dispose();
                    isf.Dispose();
                }
                catch
                {
                }
            }
        }
Esempio n. 54
0
        private void UploadFile()
        {
            var updateIe = App.ViewModel.AllToUpdateItems.AsQueryable();

            client.UploadCompleted += client_UploadCompleted;
            System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            foreach (ToDoItem uploadItem in updateIe)
            {
                infoTextBlock.Text = "Uploading...";



                byte[]       b2   = System.Text.Encoding.UTF8.GetBytes(uploadItem.TxtFile);
                MemoryStream file = new MemoryStream(b2);
                //不同difference
                client.UploadAsync(skyDriveFolderID, uploadItem.ItemName, file, OverwriteOption.Overwrite);
                string imagename = uploadItem.ItemName + ".jpg";
                if (isf.FileExists(imagename))
                {
                    System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.OpenFile(imagename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    client.UploadAsync(skyDriveFolderID_image, imagename, PhotoStream, OverwriteOption.Overwrite);
                }
            }
        }
Esempio n. 55
0
 public void GetUserStoreForSite_ThrowsNotSupported()
 {
     Assert.Throws <NotSupportedException>(() => IsolatedStorageFile.GetUserStoreForSite());
 }
Esempio n. 56
0
 public void Delete()
 {
     Storage.DeleteFile(systemFilename);
 }
Esempio n. 57
0
        private void LoadSettings()
        {
            DatabaseManager.m_LastConnection.Clear();
            string connectionHistoryFile = this.GetConnectionHistoryFile();

            System.IO.StreamReader streamReader = null;
            try
            {
                if (Command.ConfigFile.Debug)
                {
                    if (!System.IO.File.Exists(connectionHistoryFile))
                    {
                        return;
                    }
                    streamReader = new System.IO.StreamReader(connectionHistoryFile);
                }
                else
                {
                    System.IO.IsolatedStorage.IsolatedStorageFile store = System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(System.IO.IsolatedStorage.IsolatedStorageScope.User | System.IO.IsolatedStorage.IsolatedStorageScope.Assembly, null, null);
                    streamReader = new System.IO.StreamReader(new System.IO.IsolatedStorage.IsolatedStorageFileStream(System.IO.Path.GetFileName(connectionHistoryFile), System.IO.FileMode.Open, store));
                }
                if (streamReader != null)
                {
                    while (!streamReader.EndOfStream)
                    {
                        string text = streamReader.ReadLine();
                        if (string.IsNullOrEmpty(text))
                        {
                            break;
                        }
                        if (text.StartsWith("#"))
                        {
                            if (!text.StartsWith("#Last Database type: "))
                            {
                                continue;
                            }
                            string value = text.Replace("#Last Database type: ", "").Trim();
                            try
                            {
                                DatabaseManager.lastDatabaseType = (DatabaseManager.DatabaseType)System.Enum.Parse(typeof(DatabaseManager.DatabaseType), value, true);
                                Log.WriteLine("Get last DatabaseType: " + DatabaseManager.lastDatabaseType);
                                continue;
                            }
                            catch (System.Exception)
                            {
                                continue;
                            }
                        }
                        int    num    = text.IndexOf(',');
                        string value2 = text.Substring(0, num);
                        string item   = text.Substring(num + 1);
                        DatabaseManager.DatabaseType             key = (DatabaseManager.DatabaseType)System.Enum.Parse(typeof(DatabaseManager.DatabaseType), value2);
                        System.Collections.Generic.List <string> list;
                        if (!DatabaseManager.m_LastConnection.TryGetValue(key, out list))
                        {
                            list = new System.Collections.Generic.List <string>();
                            DatabaseManager.m_LastConnection.Add(key, list);
                        }
                        list.Add(item);
                    }
                }
            }
            catch (System.IO.FileNotFoundException)
            {
            }
            catch (System.Exception ex)
            {
                Log.WriteLine(ex.ToString());
            }
            finally
            {
                if (streamReader != null)
                {
                    streamReader.Close();
                }
            }
        }
 /// <include file='doc\IsolatedStorageFileStream.uex' path='docs/doc[@for="IsolatedStorageFileStream.IsolatedStorageFileStream5"]/*' />
 public IsolatedStorageFileStream(String path, FileMode mode,
                                  FileAccess access, FileShare share, IsolatedStorageFile isf)
     : this(path, mode, access, share, DefaultBufferSize, isf)
 {
 }
        /// <include file='doc\IsolatedStorageFileStream.uex' path='docs/doc[@for="IsolatedStorageFileStream.IsolatedStorageFileStream7"]/*' />
        public IsolatedStorageFileStream(String path, FileMode mode,
                                         FileAccess access, FileShare share, int bufferSize,
                                         IsolatedStorageFile isf)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if ((path.Length == 0) || path.Equals(s_BackSlash))
            {
                throw new ArgumentException(
                          Environment.GetResourceString(
                              "IsolatedStorage_path"));
            }

            ulong    oldFileSize = 0, newFileSize;
            bool     fNewFile = false, fLock = false;
            FileInfo fOld;

            if (isf == null)
            {
                m_OwnedStore = true;
                isf          = IsolatedStorageFile.GetUserStoreForDomain();
            }

            m_isf = isf;

            FileIOPermission fiop =
                new FileIOPermission(FileIOPermissionAccess.AllAccess,
                                     m_isf.RootDirectory);

            fiop.Assert();
            fiop.PermitOnly();

            m_GivenPath = path;
            m_FullPath  = m_isf.GetFullPath(m_GivenPath);

            try { // for finally Unlocking locked store
                  // Cache the old file size if the file size could change
                  // Also find if we are going to create a new file.

                switch (mode)
                {
                case FileMode.CreateNew:        // Assume new file
                    fNewFile = true;
                    break;

                case FileMode.Create:           // Check for New file & Unreserve
                case FileMode.OpenOrCreate:     // Check for new file
                case FileMode.Truncate:         // Unreserve old file size
                case FileMode.Append:           // Check for new file

                    m_isf.Lock();               // oldFileSize needs to be
                                                // protected
                    fLock = true;               // Lock succeded

                    try {
                        fOld        = new FileInfo(m_FullPath);
                        oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)fOld.Length);
                    } catch (Exception e) {
                        if (e is FileNotFoundException)
                        {
                            fNewFile = true;
                        }
                    }

                    break;

                case FileMode.Open:             // Open existing, else exception
                    break;

                default:
                    throw new ArgumentException(
                              Environment.GetResourceString(
                                  "IsolatedStorage_FileOpenMode"));
                }

                if (fNewFile)
                {
                    m_isf.ReserveOneBlock();
                }

                try {
                    m_fs = new
                           FileStream(m_FullPath, mode, access, share, bufferSize,
                                      false, m_GivenPath, true);
                } catch (Exception) {
                    if (fNewFile)
                    {
                        m_isf.UnreserveOneBlock();
                    }

                    throw;
                }

                // make adjustment to the Reserve / Unreserve state

                if ((fNewFile == false) &&
                    ((mode == FileMode.Truncate) || (mode == FileMode.Create)))
                {
                    newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length);

                    if (oldFileSize > newFileSize)
                    {
                        m_isf.Unreserve(oldFileSize - newFileSize);
                    }
                    else if (newFileSize > oldFileSize)     // Can this happen ?
                    {
                        m_isf.Reserve(newFileSize - oldFileSize);
                    }
                }
            } finally {
                if (fLock)
                {
                    m_isf.Unlock();
                }
            }
        }
Esempio n. 60
0
 public IsolatedStorageFile(string filename, Storage storage, IsolatedStorageDirectory directory)
     : this(filename, () => storage, directory)
 {
 }