/// <summary> /// Instance constructor. Ensures that the storage location in Isolated Storage is prepared /// for reading and writing. This class stores each individual field of the CacheItem into its own /// file inside the directory specified by itemDirectoryRoot. /// </summary> /// <param name="storage">Isolated Storage area to use. May not be null.</param> /// <param name="itemDirectoryRoot">Complete path in Isolated Storage where the cache item should be stored. May not be null.</param> /// <param name="encryptionProvider">Encryption provider</param> public IsolatedStorageCacheItem(IsolatedStorageFile storage, string itemDirectoryRoot, IStorageEncryptionProvider encryptionProvider) { if (storage == null) { throw new ArgumentNullException("storage"); } int retriesLeft = MaxRetries; while (true) { // work around - attempt to write a file in the folder to determine whether delayed io // needs to be processed // since only a limited number of retries will be attempted, some extreme cases may // still fail if file io is deferred long enough. // while it's still possible that the deferred IO is still pending when the item that failed // to be added is removed by the cleanup code, thus making the cleanup fail, // the item should eventually be removed (by the original removal) try { storage.CreateDirectory(itemDirectoryRoot); // try to write a file // if there is a pending operation or the folder is gone, this should find the problem // before writing an actual field is attempted using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(itemDirectoryRoot + @"\sanity-check.txt", FileMode.Create, FileAccess.Write, FileShare.None, storage)) { } break; } catch (UnauthorizedAccessException) { // there are probably pending operations on the directory - retry if allowed if (retriesLeft-- > 0) { Thread.Sleep(RetryDelayInMilliseconds); continue; } throw; } catch (DirectoryNotFoundException) { // a pending deletion on the directory was processed before creating the file // but after attempting to create it - retry if allowed if (retriesLeft-- > 0) { Thread.Sleep(RetryDelayInMilliseconds); continue; } throw; } } keyField = new IsolatedStorageCacheItemField(storage, "Key", itemDirectoryRoot, encryptionProvider); valueField = new IsolatedStorageCacheItemField(storage, "Val", itemDirectoryRoot, encryptionProvider); scavengingPriorityField = new IsolatedStorageCacheItemField(storage, "ScPr", itemDirectoryRoot, encryptionProvider); refreshActionField = new IsolatedStorageCacheItemField(storage, "RA", itemDirectoryRoot, encryptionProvider); expirationsField = new IsolatedStorageCacheItemField(storage, "Exp", itemDirectoryRoot, encryptionProvider); lastAccessedField = new IsolatedStorageCacheItemField(storage, "LA", itemDirectoryRoot, encryptionProvider); }
public void MoveFile() { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly(); // Mare sure to remove them if they exist already if (isf.FileExists("file")) { isf.DeleteFile("file"); } if (isf.FileExists("file-new")) { isf.DeleteFile("file-new"); } if (isf.FileExists("subdir/subfile")) { isf.DeleteFile("subdir/subfile"); } if (isf.FileExists("subdir/subfile-new")) { isf.DeleteFile("subdir/subfile-new"); } isf.CreateFile("file").Close(); Assert.AreEqual(true, isf.FileExists("file"), "#A0"); // Same file isf.MoveFile("file", "file"); Assert.AreEqual(true, isf.FileExists("file"), "#A0-1"); isf.MoveFile("file", "file-new"); Assert.AreEqual(false, isf.FileExists("file"), "#A1"); Assert.AreEqual(true, isf.FileExists("file-new"), "#A2"); isf.CreateDirectory("subdir"); isf.CreateFile("subdir/subfile").Close(); isf.MoveFile("subdir/subfile", "subdir/subfile-new"); Assert.AreEqual(false, isf.FileExists("subdir/subfile"), "#B0"); Assert.AreEqual(true, isf.FileExists("subdir/subfile-new"), "#B1"); try { isf.MoveFile(String.Empty, "file-new-new"); Assert.Fail("#Exc1"); } catch (ArgumentException) { } try { isf.MoveFile(" ", "file-new-new"); Assert.Fail("#Exc2"); } catch (ArgumentException e) { Console.WriteLine(e); } try { isf.MoveFile("doesntexist", "file-new-new"); Assert.Fail("#Exc3"); } catch (FileNotFoundException) { } // CopyFile is throwing a DirectoryNotFoundException here. try { isf.MoveFile("doesnexist/doesntexist", "file-new-new"); Assert.Fail("#Exc4"); } catch (FileNotFoundException) { } // I'd have expected a DirectoryNotFoundException here. try { isf.MoveFile("file-new", "doesntexist/doesntexist"); Assert.Fail("#Exc5"); } catch (IsolatedStorageException) { } // Out of storage dir try { isf.MoveFile("file-new", "../../file-new"); Assert.Fail("#Exc6"); } catch (IsolatedStorageException) { } isf.Remove(); isf.Close(); isf.Dispose(); }
public void CopyFile() { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly(); if (isf.FileExists("file")) { isf.DeleteFile("file"); } if (isf.FileExists("file-new")) { isf.DeleteFile("file-new"); } isf.CreateFile("file").Close(); isf.CopyFile("file", "file-new"); Assert.AreEqual(true, isf.FileExists("file"), "#A0"); Assert.AreEqual(true, isf.FileExists("file-new"), "#A1"); // At this point 'file-exists' already exists. isf.CopyFile("file", "file-new", true); Assert.AreEqual(true, isf.FileExists("file"), "#B0"); Assert.AreEqual(true, isf.FileExists("file-new"), "#B1"); isf.CreateDirectory("subdir"); isf.CreateFile("subdir/subfile").Close(); isf.CopyFile("subdir/subfile", "subdir/subfile-new"); Assert.AreEqual(true, isf.FileExists("subdir/subfile"), "#C0"); Assert.AreEqual(true, isf.FileExists("subdir/subfile-new"), "#C1"); try { isf.CopyFile("file", "file-new"); Assert.Fail("#Exc0"); } catch (IsolatedStorageException) { } // Using the same file name is failing for even when passing override=true. try { isf.CopyFile("file-new", "file-new", true); Assert.Fail("#Exc1"); } catch (IsolatedStorageException) { } try { isf.CopyFile("file-new", "file-new", false); Assert.Fail("#Exc2"); } catch (IsolatedStorageException) { } // Remove 'file-new' for cleaness purposes. isf.DeleteFile("file-new"); try { isf.CopyFile("doesntexist", "file-new", false); Assert.Fail("#Exc3"); } catch (FileNotFoundException) { } try { isf.CopyFile("doesnexist/doesntexist", "file-new", false); Assert.Fail("#Exc4"); } catch (DirectoryNotFoundException) { } // I'd have expected a DirectoryNotFoundException here. try { isf.CopyFile("file", "doesntexist/doesntexist"); Assert.Fail("#Exc5"); } catch (IsolatedStorageException) { } // Out of storage dir try { isf.CopyFile("file", "../../file"); Assert.Fail("#Exc6"); } catch (IsolatedStorageException) { } try { isf.CopyFile("../file", "file-new"); Assert.Fail("#Exc7"); } catch (IsolatedStorageException) { } // We are creating a subdirectory and files within it, so remove it just in case. isf.Remove(); isf.Close(); isf.Dispose(); }
/// <summary> /// /// </summary> /// <param name="asynchronousResult"></param> private void downloadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; HttpWebRequest request = reqState.request; string callbackId = reqState.options.CallbackId; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); // send a progress change event DispatchFileTransferProgress(0, response.ContentLength, callbackId); using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create any directories in the path that do not exist string directoryName = getDirectoryName(reqState.options.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // create the file if not exists if (!isoFile.FileExists(reqState.options.FilePath)) { var file = isoFile.CreateFile(reqState.options.FilePath); file.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = response.ContentLength; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(response.GetResponseStream())) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0 && !reqState.isCancelled) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } System.Threading.Thread.Sleep(1); } } } } if (reqState.isCancelled) { isoFile.DeleteFile(reqState.options.FilePath); } } if (reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)), callbackId); } else { File.FileEntry entry = new File.FileEntry(reqState.options.FilePath); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } } catch (IsolatedStorageException) { // Trying to write the file somewhere within the IsoStorage. DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } catch (SecurityException) { // Trying to write the file somewhere not allowed. DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } catch (WebException webex) { // TODO: probably need better work here to properly respond with all http status codes back to JS // Right now am jumping through hoops just to detect 404. HttpWebResponse response = (HttpWebResponse)webex.Response; if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound) || webex.Status == WebExceptionStatus.UnknownError) { // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!! // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away." // FACEPALM // Or just cast it to an int, whiner ... -jm int statusCode = (int)response.StatusCode; string body = ""; using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(streamResponse)) { body = streamReader.ReadToEnd(); } } FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), callbackId); } else { lock (reqState) { if (!reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); } else { Debug.WriteLine("It happened"); } } } } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } //System.Threading.Thread.Sleep(1000); if (InProcDownloads.ContainsKey(reqState.options.Id)) { InProcDownloads.Remove(reqState.options.Id); } }
public static void CreateDirectory(string a_name) { s_isoStore.CreateDirectory(a_name); }
public override void CreateFolder(string path) { IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); store.CreateDirectory(path); }
public void unzip(string srcFilePath, string destPath, int type) { using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) { // DEBUG here to copy file from dll to isostore ... // this is only really needed if you want to test with a file in your package/project StreamResourceInfo fileResourceStreamInfo = Application.GetResourceStream(new Uri(srcFilePath, UriKind.Relative)); if (fileResourceStreamInfo != null) { using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream)) { byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length); // This will truncate/overwrite an existing file, or using (IsolatedStorageFileStream outFile = appStorage.OpenFile(srcFilePath, FileMode.Create)) { using (var writer = new BinaryWriter(outFile)) { writer.Write(data); } } } } if (type == Replace) { DeleteDirectoryRecursively(appStorage, destPath); } IsolatedStorageFileStream zipStream = null; ZipArchive zipArch = null; try { zipStream = new IsolatedStorageFileStream(srcFilePath, FileMode.Open, FileAccess.Read, appStorage); } catch (Exception) { Debug.WriteLine("File not found :: " + srcFilePath); return; } if (zipStream != null) { zipArch = new ZipArchive(zipStream); } if (zipArch != null) { int totalFiles = zipArch.FileNames.Count(); int current = 0; try { foreach (string filename in zipArch.FileNames) { string destFilePath = destPath + "/" + filename; string directoryName = getDirectoryName(destFilePath); //Debug.WriteLine("upacking file : " + filename + " to : " + destFilePath); if (!appStorage.DirectoryExists(directoryName)) { appStorage.CreateDirectory(directoryName); } using (Stream readStream = zipArch.GetFileStream(filename)) { if (readStream != null) { if (type == Merge) { using (FileStream outStream = new IsolatedStorageFileStream(destFilePath, FileMode.OpenOrCreate, FileAccess.Write, appStorage)) { WriteStreamToPath(readStream, outStream); } FileUnzipProgress progEvt = new FileUnzipProgress(totalFiles, current++); } else { using (FileStream outStream = new IsolatedStorageFileStream(destFilePath, FileMode.OpenOrCreate, FileAccess.Write, appStorage)) { WriteStreamToPath(readStream, outStream); FileUnzipProgress progEvt = new FileUnzipProgress(totalFiles, current++); } } } } } zipStream.Close(); } catch (Exception) { Debug.WriteLine("File not found :: " + srcFilePath); } } } }
// Code to execute if a navigation fails private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { if (Debugger.IsAttached) { // A navigation has failed; break into the debugger Debugger.Break(); } else { //ATT: Programatically exiting app... if (e.Exception.Message == "Cannot go back when CanGoBack is false.") { return; } string sException = "RootFrame_NavigationFailed...\n\nMessage:\n" + e.Exception.Message + "\n\nStack Trace:\n" + e.Exception.StackTrace; IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); string sPath = "System"; if (!store.DirectoryExists(sPath)) { store.CreateDirectory(sPath); } sPath += "\\Events"; if (!store.DirectoryExists(sPath)) { store.CreateDirectory(sPath); } DateTime dNow = DateTime.Now; sPath += "\\"; sPath += dNow.Year.ToString() + "-"; if (dNow.Month < 10) { sPath += "0"; } sPath += dNow.Month.ToString() + "-"; if (dNow.Day < 10) { sPath += "0"; } sPath += dNow.Day.ToString(); sPath += "_"; if (dNow.Hour < 10) { sPath += "0"; } sPath += dNow.Hour.ToString() + "-"; if (dNow.Minute < 10) { sPath += "0"; } sPath += dNow.Minute.ToString() + "-"; if (dNow.Second < 10) { sPath += "0"; } sPath += dNow.Second.ToString(); string sPathWrk = sPath; int i = 0; for (;;) { sPathWrk = sPath + "_" + i.ToString(); if (!store.FileExists(sPathWrk + ".error")) { break; } i++; } sPath = sPathWrk + ".error"; IsolatedStorageFileStream stream = store.CreateFile(sPath); StreamWriter sw = new StreamWriter(stream); sw.Write(sException); sw.Close(); stream.Close(); MessageBox.Show(sException); } }
//----------------------------------------------------------------------------------------------------------------- //Prüfen ob Return gedrückt wurde //----------------------------------------------------------------------------------------------------------------- private void TBFolderName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { //Prüfen ob Return gedrückt wurde string tempkey = Convert.ToString(e.Key); if (tempkey == "Enter") { //";" Zeichen herauslöschen TBFolderName.Text = Regex.Replace(TBFolderName.Text, ";", ""); //Prüfen ob noch Zeichen vorhanden if (TBFolderName.Text.Length > 0) { //Prüfen ob leere Eingabe und zurücksetzen bool temp = Regex.IsMatch(TBFolderName.Text, @"^[a-zA-Z0-9 ]+$"); temp = true; if (temp == false) { MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName); TBFolderName.Text = FolderName; } else { if (FolderName == TBFolderName.Text) { NavigationService.GoBack(); } else { //Prüfen ob Ordner bereits besteht if (!file.DirectoryExists("/Folders/" + TBFolderName.Text)) { try { //Ordnerdatei laden IsolatedStorageFileStream filestream = file.OpenFile("Folders.dat", FileMode.Open); StreamReader sr = new StreamReader(filestream); string FoldersAll = sr.ReadToEnd(); filestream.Close(); FoldersAll = FoldersAll.TrimEnd(new char[] { '\r', '\n' }); //Ordner umbenennen file.CreateDirectory("Folders/" + TBFolderName.Text); string[] files = file.GetFileNames("/Folders/" + FolderName + "/"); foreach (string file2 in files) { file.MoveFile("/Folders/" + FolderName + "/" + file2, "Folders/" + TBFolderName.Text + "/" + file2); } file.DeleteDirectory("/Folders/" + FolderName); file.CreateDirectory("Thumbs/" + TBFolderName.Text); string[] files2 = file.GetFileNames("/Thumbs/" + FolderName + "/"); foreach (string file2 in files2) { file.MoveFile("/Thumbs/" + FolderName + "/" + file2, "Thumbs/" + TBFolderName.Text + "/" + file2); } file.MoveFile("/Thumbs/" + FolderName + ".dat", "Thumbs/" + TBFolderName.Text + ".dat"); file.DeleteDirectory("/Thumbs/" + FolderName); //Ordnerdatei ändern FoldersAll = FoldersAll.Replace("/" + FolderName + "/", "/" + TBFolderName.Text + "/"); //Neue Ordner Datei erstellen filestream = file.CreateFile("Folders.dat"); StreamWriter sw = new StreamWriter(filestream); sw.WriteLine(FoldersAll); sw.Flush(); filestream.Close(); //Navigation zurück NavigationService.GoBack(); } catch { MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName); TBFolderName.Text = FolderName; } } //Wenn Ordner bereits besteht else { MessageBox.Show(Lockscreen_Swap.AppResx.ErrorName); TBFolderName.Text = FolderName; } } } } else { MessageBox.Show(Lockscreen_Swap.AppResx.ErrorEnterName); TBFolderName.Text = FolderName; } //Focus zurücksetzen //Focus(); } }
private void GetFileOrDirectory(string options, bool getDirectory) { if (!LoadFileOptions(options)) { return; } if (fileOptions == null) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { if ((string.IsNullOrEmpty(fileOptions.Path)) || (string.IsNullOrEmpty(fileOptions.FullPath))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR)); return; } string path; try { path = Path.Combine(fileOptions.FullPath + "/", fileOptions.Path); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR)); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isFile = isoFile.FileExists(path); bool isDirectory = isoFile.DirectoryExists(path); bool create = (fileOptions.CreatingOpt == null) ? false : fileOptions.CreatingOpt.Create; bool exclusive = (fileOptions.CreatingOpt == null) ? false : fileOptions.CreatingOpt.Exclusive; if (create) { if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR)); return; } if ((getDirectory) && (!isDirectory)) { isoFile.CreateDirectory(path); } else { if ((!getDirectory) && (!isFile)) { IsolatedStorageFileStream fileStream = isoFile.CreateFile(path); fileStream.Close(); } } } else { if ((!isFile) && (!isDirectory)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR)); return; } if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR)); return; } } FileEntry entry = FileEntry.GetEntry(path); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry)); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR)); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR)); } } }
public void requestFileSystem(string options) { if (!LoadFileOptions(options)) { return; } try { if (fileOptions.Size != 0) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { long availableSize = isoFile.AvailableFreeSpace; if (fileOptions.Size > availableSize) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR)); return; } } } if (fileOptions.FileSystemType == PERSISTENT) { // TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/")))); } else if (fileOptions.FileSystemType == TEMPORARY) { using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoStorage.FileExists(TMP_DIRECTORY_NAME)) { isoStorage.CreateDirectory(TMP_DIRECTORY_NAME); } } string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/"; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder)))); } else if (fileOptions.FileSystemType == RESOURCE) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource"))); } else if (fileOptions.FileSystemType == APPLICATION) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application"))); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR)); } } //catch (SecurityException) //{ // DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR)); //} //catch (FileNotFoundException) //{ // DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR)); //} catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR)); } } }
public async Task DownloadPosters() { await DownloadFile(MovieFilmPostersFileName, false); if (!Config.AnimateLockscreen) { return; } object o = await ReadMoviePosters(); if (o == null || !(o is JObject)) { return; } JObject data = (JObject)o; bool downloadFiles = true; IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); string folder = "Shared\\ShellContent"; if (!isf.DirectoryExists(folder)) { isf.CreateDirectory(folder); } else { if (isf.GetLastWriteTime(folder) >= isf.GetLastWriteTime(BaseStorageHelper.MovieFilmPostersFileName) && isf.GetFileNames("*.jpg").Length > 0) { downloadFiles = false; } } if (downloadFiles) { AsyncWebClient awc = new AsyncWebClient(); HashSet <string> newPosters = new HashSet <string>(); foreach (var item in data) { string filename = Path.GetFileName((string)item.Value); newPosters.Add(filename); string localPath = String.Format("{0}\\{1}", folder, filename); if (!isf.FileExists(localPath)) { await awc.DownloadFileAsync((string)item.Value, filename, folder); } } HashSet <string> allPosters = new HashSet <string>(isf.GetFileNames(String.Format("{0}\\*.*", folder))); allPosters.ExceptWith(newPosters); foreach (var file in allPosters) { try { isf.DeleteFile(file); } catch { } } allPosters.ExceptWith(newPosters); foreach (var file in allPosters) { try { isf.DeleteFile(file); } catch { } } } }
public void CreateIsolatedStorage() { storage = IsolatedStorageFile.GetUserStoreForDomain(); storage.CreateDirectory(DirectoryName); }
public static void CreateFolder(string path) { _store.CreateDirectory(path); }
/* Used to create a record file one is not found. Can also be used to reset records. */ public static void CreateRecord() { string directory = "TileCrusher"; string fileName = "Records.txt"; IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication(); //create directory fileStorage.CreateDirectory(directory); IsolatedStorageFileStream fs = new IsolatedStorageFileStream(directory + "\\" + fileName, System.IO.FileMode.Create, fileStorage); StreamWriter fileWrite = new StreamWriter(fs); //(re)set initial data hours = 0; minutes = 0; seconds = 0; totalTime = "00:00"; completionRate = "0"; turnTotal = 0; levelsCompleted = 0; lossCount = 0; rageCount = 0; fileWrite.WriteLine(hours); fileWrite.WriteLine(minutes); fileWrite.WriteLine(seconds); fileWrite.WriteLine(totalTime); //total time played fileWrite.WriteLine(completionRate); //completion rate fileWrite.WriteLine(turnTotal); //total turns fileWrite.WriteLine(levelsCompleted); //number of levels completed fileWrite.WriteLine(lossCount); //number of losses fileWrite.WriteLine(rageCount); //number of quits before level's complete. If player finished level previously, this doesn't apply //set up bool arrays & write to file for (int i = 0; i < MAX_LEVELS; i++) { finishedLevel[i] = false; fileWrite.Write(finishedLevel[i] + " "); } //move to next line fileWrite.WriteLine(); for (int j = 0; j < MAX_LEVELS; j++) { if (j <= 9) //first 10 levels are always unlocked. { lockedLevel[j] = false; } else { lockedLevel[j] = true; } fileWrite.Write(lockedLevel[j] + " "); } //fileCreated = true; fileWrite.Close(); //This line is important! fs.Close(); //This one too! }
public void CreateDirectory(string directoryName) { IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null); isoFile.CreateDirectory(directoryName); }
public static void AddSysEvent(string sText, bool bErr = false, string sCustTimeStampPart = "") { IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); string sPath = "System"; if (!store.DirectoryExists(sPath)) { store.CreateDirectory(sPath); } sPath += "\\Events"; if (!store.DirectoryExists(sPath)) { store.CreateDirectory(sPath); } sPath += "\\"; if (bErr) { sPath += "ERR_"; } else { sPath += "INF_"; } if (sCustTimeStampPart.Length == 0) { DateTime dNow = DateTime.Now; sPath += dNow.Year.ToString() + "-"; if (dNow.Month < 10) { sPath += "0"; } sPath += dNow.Month.ToString() + "-"; if (dNow.Day < 10) { sPath += "0"; } sPath += dNow.Day.ToString(); sPath += "_"; if (dNow.Hour < 10) { sPath += "0"; } sPath += dNow.Hour.ToString() + "-"; if (dNow.Minute < 10) { sPath += "0"; } sPath += dNow.Minute.ToString() + "-"; if (dNow.Second < 10) { sPath += "0"; } sPath += dNow.Second.ToString(); } else { sPath += sCustTimeStampPart; } string sExt; if (bErr) { sExt = ".error"; } else { sExt = ".info"; } string sPathWrk = sPath; if (sCustTimeStampPart.Length == 0) { int i = 0; for (;;) { sPathWrk = sPath + "_" + i.ToString(); if (!store.FileExists(sPathWrk + sExt)) { break; } i++; } } sPath = sPathWrk + sExt; IsolatedStorageFileStream stream = store.CreateFile(sPath); StreamWriter sw = new StreamWriter(stream); sw.Write(sText); sw.Close(); stream.Close(); }
//*********************************************************************************************************************** //*********************************************************************************************************************** /// <summary> /// Crée un nouveau marque page. /// </summary> /// <param name="Name">Nom du marque page.</param> /// <param name="Value">Marque page.</param> //----------------------------------------------------------------------------------------------------------------------- public void Add <T> (string Name, T Value) { //------------------------------------------------------------------------------------------------------------------- #region // Implémentation de la Procédure //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- try { //--------------------------------------------------------------------------------------------------------------- if (this.Iso != null) { //----------------------------------------------------------------------------------------------------------- // Le dossier Bookmarks doit exister //----------------------------------------------------------------------------------------------------------- if (!Iso.DirectoryExists("Bookmarks")) { Iso.CreateDirectory("Bookmarks"); } //----------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------- // Convertion du nom en clé //----------------------------------------------------------------------------------------------------------- string Pattern = "Bookmarks/{*-" + ToBaseName(Name) + "}"; //----------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------- // Suppression du fichier //----------------------------------------------------------------------------------------------------------- foreach (string FileID in Iso.GetFileNames(Pattern)) { //------------------------------------------------------------------------------------------------------- Iso.DeleteFile("Bookmarks/" + FileID); //------------------------------------------------------------------------------------------------------- } //----------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------- // Enregistrement des Informations //----------------------------------------------------------------------------------------------------------- string BaseName = ToBaseName(Name); string BookmarkFile = string.Format("Bookmarks/{{{0}-{1}}}", DateTime.Now. ToString("yyyyMMdd-HHmmss"), BaseName); //----------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------- // Ecriture du fichier //----------------------------------------------------------------------------------------------------------- using (var File = Iso.CreateFile(BookmarkFile)) { //------------------------------------------------------------------------------------------------------- using (var Sw = new StreamWriter(File)) { //--------------------------------------------------------------------------------------------------- XmlSerializer Xs = new XmlSerializer(typeof(T)); using (StringWriter St = new StringWriter()) { XmlWriter writer = XmlWriter.Create(St); Xs.Serialize(writer, Value); Sw.Write(St.ToString()); } //--------------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------------------- } //----------------------------------------------------------------------------------------------------------- } //--------------------------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------------------------------- catch {} //------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------- #endregion //------------------------------------------------------------------------------------------------------------------- }
/// <summary> /// Starts or resume playing audio file /// </summary> /// <param name="filePath">The name of the audio file</param> /// <summary> /// Starts or resume playing audio file /// </summary> /// <param name="filePath">The name of the audio file</param> public void startPlaying(string filePath) { if (this.recorder != null) { InvokeCallback(MediaError, MediaErrorRecordModeSet, false); //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet),false); return; } if (this.player == null || this.player.Source.AbsolutePath.LastIndexOf(filePath) < 0) { try { // this.player is a MediaElement, it must be added to the visual tree in order to play PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { Grid grid = page.FindName("LayoutRoot") as Grid; if (grid != null) { this.player = grid.FindName("playerMediaElement") as MediaElement; if (this.player == null) // still null ? { this.player = new MediaElement(); this.player.Name = "playerMediaElement"; grid.Children.Add(this.player); this.player.Visibility = Visibility.Visible; } if (this.player.CurrentState == System.Windows.Media.MediaElementState.Playing) { this.player.Stop(); // stop it! } this.player.Source = null; // Garbage collect it. this.player.MediaOpened += MediaOpened; this.player.MediaEnded += MediaEnded; this.player.MediaFailed += MediaFailed; } } } this.audioFile = filePath; Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute); if (uri.IsAbsoluteUri) { this.player.Source = uri; } else { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { // try to unpack it from the dll into isolated storage StreamResourceInfo fileResourceStreamInfo = Application.GetResourceStream(new Uri(filePath, UriKind.Relative)); if (fileResourceStreamInfo != null) { using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream)) { byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length); string[] dirParts = filePath.Split('/'); string dirName = ""; for (int n = 0; n < dirParts.Length - 1; n++) { dirName += dirParts[n] + "/"; } if (!isoFile.DirectoryExists(dirName)) { isoFile.CreateDirectory(dirName); } using (IsolatedStorageFileStream outFile = isoFile.OpenFile(filePath, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(outFile)) { writer.Write(data); } } } } } if (isoFile.FileExists(filePath)) { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile)) { this.player.SetSource(stream); } } else { InvokeCallback(MediaError, MediaErrorPlayModeSet, false); //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, 1), false); return; } } } this.SetState(PlayerState_Starting); } catch (Exception e) { Debug.WriteLine("Error in AudioPlayer::startPlaying : " + e.Message); InvokeCallback(MediaError, MediaErrorStartingPlayback, false); //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback),false); } } else { if (this.state != PlayerState_Running) { this.player.Play(); this.SetState(PlayerState_Running); } else { InvokeCallback(MediaError, MediaErrorResumeState, false); //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState),false); } } }
public void sync(string options) { TransferOptions downloadOptions = null; HttpWebRequest webRequest = null; string callbackId; try { // options.src, options.type, options.headers, options.id string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options); downloadOptions = new TransferOptions(); downloadOptions.Url = optionStrings[0]; bool trustAll = false; downloadOptions.TrustAllHosts = trustAll; downloadOptions.Id = optionStrings[1]; downloadOptions.FilePath = "content_sync/downloads/" + downloadOptions.Id; if (String.Equals(optionStrings[2], "replace")) { downloadOptions.Type = Replace; } else { downloadOptions.Type = Merge; } downloadOptions.Headers = optionStrings[3]; bool copyCordovaAssets = false; bool.TryParse(optionStrings[4], out copyCordovaAssets); downloadOptions.CopyCordovaAssets = copyCordovaAssets; bool copyRootApp = false; bool.TryParse(optionStrings[5], out copyRootApp); downloadOptions.CopyRootApp = copyRootApp; downloadOptions.Timeout = Convert.ToInt32(optionStrings[6]); downloadOptions.CallbackId = callbackId = optionStrings[7]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { // not sure if we still need this // is the URL a local app file? if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:")) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//", ""); // pre-emptively create any directories in the FilePath that do not exist string directoryName = getDirectoryName(downloadOptions.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // just copy from one area of iso-store to another ... if (isoFile.FileExists(downloadOptions.Url)) { isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath); } else { // need to unpack resource from the dll Uri uri = new Uri(cleanUrl, UriKind.Relative); var resource = Application.GetResourceStream(uri); if (resource != null) { // create the file destination if (!isoFile.FileExists(downloadOptions.FilePath)) { var destFile = isoFile.CreateFile(downloadOptions.FilePath); destFile.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Create, FileAccess.Write, isoFile)) { long totalBytes = resource.Stream.Length; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(resource.Stream)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0) { writer.Write(buffer); DispatchSyncProgress(bytesRead, totalBytes, 1, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } } } } } } } } string result = "{ \"localPath\": \"" + downloadOptions.FilePath + "\" , \"Id\" : \"" + downloadOptions.Id + "\"}"; if (result != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, 0), callbackId); } return; } else { // otherwise it is web-bound, we will actually download it //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); } } catch (Exception /*ex*/) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new SyncError(InvalidUrlError, downloadOptions.Url, null, 0))); return; } if (downloadOptions != null && webRequest != null) { DownloadRequestState state = new DownloadRequestState(); state.options = downloadOptions; state.request = webRequest; InProcDownloads[downloadOptions.Id] = state; if (!string.IsNullOrEmpty(downloadOptions.Headers)) { Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } try { webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); } catch (WebException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new SyncError(InvalidUrlError, downloadOptions.Url, null, 0))); } // dispatch an event for progress ( 0 ) lock (state) { if (!state.isCancelled) { var plugRes = new PluginResult(PluginResult.Status.OK, new SyncProgress()); plugRes.KeepCallback = true; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } } } }
public async void download(string options) { TransferOptions downloadOptions = null; HttpWebRequest webRequest = null; string callbackId; try { // source, target, trustAllHosts, this._id, headers string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options); downloadOptions = new TransferOptions(); downloadOptions.Url = optionStrings[0]; downloadOptions.FilePath = optionStrings[1]; bool trustAll = false; bool.TryParse(optionStrings[2], out trustAll); downloadOptions.TrustAllHosts = trustAll; downloadOptions.Id = optionStrings[3]; downloadOptions.Headers = optionStrings[4]; downloadOptions.CallbackId = callbackId = optionStrings[5]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { // is the URL a local app file? if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:")) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//", ""); // pre-emptively create any directories in the FilePath that do not exist string directoryName = getDirectoryName(downloadOptions.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // just copy from one area of iso-store to another ... if (isoFile.FileExists(downloadOptions.Url)) { isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath); } else { // need to unpack resource from the dll Uri uri = new Uri(cleanUrl, UriKind.Relative); var resource = Application.GetResourceStream(uri); if (resource != null) { // create the file destination if (!isoFile.FileExists(downloadOptions.FilePath)) { var destFile = isoFile.CreateFile(downloadOptions.FilePath); destFile.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = resource.Stream.Length; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(resource.Stream)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } } } } } } } } File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId); } return; } else { // otherwise it is web-bound, we will actually download it //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); } } catch (Exception /*ex*/) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0))); return; } if (downloadOptions != null && webRequest != null) { DownloadRequestState state = new DownloadRequestState(); state.options = downloadOptions; state.request = webRequest; InProcDownloads[downloadOptions.Id] = state; // Associate cookies with the request // This is an async call, so we need to await it in order to preserve proper control flow await CopyCookiesFromWebBrowser(webRequest); if (!string.IsNullOrEmpty(downloadOptions.Headers)) { Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } try { webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); } catch (WebException) { // eat it } // dispatch an event for progress ( 0 ) lock (state) { if (!state.isCancelled) { var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress()); plugRes.KeepCallback = true; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } } } }
/// <summary> /// Creates a directory in the storage scope. /// </summary> /// <param name="dir">The relative path of the directory to create within the storage.</param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public Task CreateDirectoryAsync(string dir) { return(Task.Factory.StartNew(() => Storage.CreateDirectory(dir))); }
/// <summary> /// Write out the current state of the director and all of its scenes. /// </summary> public void SerializeState() { // open up isolated storage using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { // if our screen manager directory already exists, delete the contents if (storage.DirectoryExists(m_sStorageDirName)) { DeleteState(storage); } // otherwise just create the directory else { storage.CreateDirectory(m_sStorageDirName); } // create a file we'll use to store the list of screens in the stack CCLog.Log("Saving CCDirector state to file: " + Path.Combine(m_sStorageDirName, m_sSaveFileName)); try { using (IsolatedStorageFileStream stream = storage.OpenFile(Path.Combine(m_sStorageDirName, m_sSaveFileName), FileMode.OpenOrCreate)) { using (StreamWriter writer = new StreamWriter(stream)) { // write out the full name of all the types in our stack so we can // recreate them if needed. foreach (CCScene scene in m_pobScenesStack) { if (scene.IsSerializable) { writer.WriteLine(scene.GetType().AssemblyQualifiedName); } else { CCLog.Log("Scene is not serializable: " + scene.GetType().FullName); } } // Write out our local state if (m_pRunningScene != null && m_pRunningScene.IsSerializable) { writer.WriteLine("m_pRunningScene"); writer.WriteLine(m_pRunningScene.GetType().AssemblyQualifiedName); } // Add my own state // [*]name=value // } } // now we create a new file stream for each screen so it can save its state // if it needs to. we name each file "ScreenX.dat" where X is the index of // the screen in the stack, to ensure the files are uniquely named int screenIndex = 0; string fileName = null; foreach (CCScene scene in m_pobScenesStack) { if (scene.IsSerializable) { fileName = string.Format(Path.Combine(m_sStorageDirName, m_sSceneSaveFileName), screenIndex); // open up the stream and let the screen serialize whatever state it wants using (IsolatedStorageFileStream stream = storage.CreateFile(fileName)) { scene.Serialize(stream); } screenIndex++; } } // Write the current running scene if (m_pRunningScene != null && m_pRunningScene.IsSerializable) { fileName = string.Format(Path.Combine(m_sStorageDirName, m_sSceneSaveFileName), "XX"); // open up the stream and let the screen serialize whatever state it wants using (IsolatedStorageFileStream stream = storage.CreateFile(fileName)) { m_pRunningScene.Serialize(stream); } } } catch (Exception ex) { CCLog.Log("Failed to serialize the CCDirector state. Erasing the save files."); CCLog.Log(ex.ToString()); DeleteState(storage); } } }
public List_Video_Follow_Drama() { InitializeComponent(); //disableProgressBar(); setUpApplicationBar(); imgCache = new ImageCache(); SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Portrait; webClient = new WebClient(); btnViewFromBegin.Background = new SolidColorBrush(Colors.White); btnViewFromBegin.Foreground = new SolidColorBrush(Colors.Black); this.lstVideoFollowDrama.Loaded += new RoutedEventHandler(lstVideoFollowDrama_Loaded); //Request to server to get Image Material webClient.OpenReadCompleted += (s1, e1) => { if (e1.Error == null) { try { bool isSpaceAvailable = IsSpaceIsAvailable(e1.Result.Length); if (isSpaceAvailable) { //Save File To Isolated Storage using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!myIsolatedStorage.DirectoryExists(folder)) { myIsolatedStorage.CreateDirectory(folder); } using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(folder + "\\" + ImageFileName, FileMode.Create, FileAccess.Write, myIsolatedStorage)) { long imgLen = e1.Result.Length; byte[] b = new byte[imgLen]; e1.Result.Read(b, 0, b.Length); isfs.Write(b, 0, b.Length); isfs.Flush(); isfs.Close(); } } LoadImageFromIsolatedStorage(folder + "\\" + ImageFileName); } else { BitmapImage bmpImg = new BitmapImage(); bmpImg.SetSource(e1.Result); imgDrama.Source = bmpImg; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }; }
/// <summary> /// 加密并保存当前时间到"独立存贮空间" (以分号(;)追加保存) /// </summary> public static void SaveDataTime(DateTime fromDate) { string fromDataTime = fromDate.ToString("MM-dd-yyyy HH:mm:ss"); string oldTime = GetDataTime().Trim(); if (!string.IsNullOrEmpty(oldTime)) { fromDataTime = oldTime + ";" + fromDataTime; //追加最后时间到左边 } fromDataTime = EncodeHelper.DesEncrypt(fromDataTime, UIConstants.IsolatedStorageEncryptKey); //加密 #region 将fromDataTime保存在"独立存贮空间" string username = fromDataTime; //按用户、域、程序集获取独立存储区 IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null); string[] myusername = isoStore.GetDirectoryNames(UIConstants.IsolatedStorageDirectoryName); IsolatedStorageFileStream isoStream1 = null; if (myusername.Length == 0) //没有目录 { //创建目录 isoStore.CreateDirectory(UIConstants.IsolatedStorageDirectoryName); //创建文件 using (isoStream1 = new IsolatedStorageFileStream(UIConstants.IsolatedStorage, FileMode.Create, isoStore)) { //写入文件 using (StreamWriter writer = new StreamWriter(isoStream1)) { writer.WriteLine(fromDataTime); } } } else { myusername = isoStore.GetFileNames(UIConstants.IsolatedStorage); if (myusername.Length == 0) //没有文件 { //创建文件 using (isoStream1 = new IsolatedStorageFileStream(UIConstants.IsolatedStorage, FileMode.Create, isoStore)) { //写入文件 using (StreamWriter writer = new StreamWriter(isoStream1)) { writer.WriteLine(fromDataTime); } } } else { using (isoStream1 = new IsolatedStorageFileStream(UIConstants.IsolatedStorage, FileMode.Open, isoStore)) { //写入文件 using (StreamWriter writer = new StreamWriter(isoStream1)) { writer.WriteLine(fromDataTime); } } } } #endregion }
void GapBrowser_Loaded(object sender, RoutedEventArgs e) { if (DesignerProperties.IsInDesignTool) { return; } // prevents refreshing web control to initial state during pages transitions if (this.IsBrowserInitialized) { return; } this.domStorageHelper = new DOMStorageHelper(this.CordovaBrowser); try { // Before we possibly clean the ISO-Store, we need to grab our generated UUID, so we can rewrite it after. string deviceUUID = ""; using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) { try { IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage); using (StreamReader reader = new StreamReader(fileStream)) { deviceUUID = reader.ReadLine(); } } catch (Exception /*ex*/) { deviceUUID = Guid.NewGuid().ToString(); } Debug.WriteLine("Updating IsolatedStorage for APP:DeviceID :: " + deviceUUID); IsolatedStorageFileStream file = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Create, FileAccess.Write, appStorage); using (StreamWriter writeFile = new StreamWriter(file)) { writeFile.WriteLine(deviceUUID); writeFile.Close(); } } StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("CordovaSourceDictionary.xml", UriKind.Relative)); if (streamInfo != null) { StreamReader sr = new StreamReader(streamInfo.Stream); //This will Read Keys Collection for the xml file XDocument document = XDocument.Parse(sr.ReadToEnd()); var files = from results in document.Descendants("FilePath") select new { path = (string)results.Attribute("Value") }; StreamResourceInfo fileResourceStreamInfo; using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) { foreach (var file in files) { fileResourceStreamInfo = Application.GetResourceStream(new Uri(file.path, UriKind.Relative)); if (fileResourceStreamInfo != null) { using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream)) { byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length); string strBaseDir = AppRoot + file.path.Substring(0, file.path.LastIndexOf(System.IO.Path.DirectorySeparatorChar)); if (!appStorage.DirectoryExists(strBaseDir)) { Debug.WriteLine("INFO: Creating Directory :: " + strBaseDir); appStorage.CreateDirectory(strBaseDir); } // This will truncate/overwrite an existing file, or using (IsolatedStorageFileStream outFile = appStorage.OpenFile(AppRoot + file.path, FileMode.Create)) { Debug.WriteLine("INFO: Writing data for " + AppRoot + file.path + " and length = " + data.Length); using (var writer = new BinaryWriter(outFile)) { writer.Write(data); } } } } else { Debug.WriteLine("ERROR: Failed to write file :: " + file.path + " did you forget to add it to the project?"); } } } } CordovaBrowser.Navigate(StartPageUri); IsBrowserInitialized = true; AttachHardwareButtonHandlers(); } catch (Exception ex) { Debug.WriteLine("ERROR: Exception in GapBrowser_Loaded :: {0}", ex.Message); } }
public void MoveDirectory() { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly(); // Mare sure to remove them if they exist already if (isf.DirectoryExists("subdir")) { isf.DeleteDirectory("subdir"); } if (isf.DirectoryExists("subdir-new")) { isf.DeleteDirectory("subdir-new"); } isf.CreateDirectory("subdir"); Assert.AreEqual(true, isf.DirectoryExists("subdir"), "#A0"); isf.MoveDirectory("subdir", "subdir-new"); Assert.AreEqual(false, isf.DirectoryExists("subdir"), "#A1"); Assert.AreEqual(true, isf.DirectoryExists("subdir-new"), "#A2"); try { isf.MoveDirectory(String.Empty, "subdir-new-new"); Assert.Fail("#Exc1"); } catch (ArgumentException) { } try { isf.MoveDirectory(" ", "subdir-new-new"); Assert.Fail("#Exc2"); } catch (ArgumentException) { } try { isf.MoveDirectory("doesntexist", "subdir-new-new"); Assert.Fail("#Exc3"); } catch (DirectoryNotFoundException) { } try { isf.MoveDirectory("doesnexist/doesntexist", "subdir-new-new"); Assert.Fail("#Exc4"); } catch (DirectoryNotFoundException) { } try { isf.MoveDirectory("subdir-new", "doesntexist/doesntexist"); Assert.Fail("#Exc5"); } catch (DirectoryNotFoundException) { } // Out of storage dir try { isf.MoveDirectory("subdir-new", "../../subdir-new"); Assert.Fail("#Exc6"); } catch (IsolatedStorageException) { } isf.Remove(); isf.Close(); isf.Dispose(); }
private void ExtractZip() { LoaderProgress(); int countZip = 0; using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { LoaderProgress(); using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("wp8.zip", FileMode.Open, FileAccess.ReadWrite)) { LoaderProgress(); UnZipper unzip = new UnZipper(fileStream); foreach (string filename in unzip.FileNamesInZip()) { Stream fileFromZip = unzip.GetFileStream(filename); if (filename.Contains("/.")) { continue; } var dicName = Path.GetDirectoryName(filename); if (!myIsolatedStorage.DirectoryExists(dicName)) { myIsolatedStorage.CreateDirectory(dicName); } StorageFolder localFolder1 = ApplicationData.Current.LocalFolder; string mystring1 = localFolder1.Path; if (fileFromZip != null) { using (var fileStream1 = new FileStream(mystring1 + "\\" + filename, FileMode.Create, FileAccess.Write)) { fileFromZip.CopyTo(fileStream1); } byte[] buffer1 = new byte[fileFromZip.Length]; //Store bytes in buffer, so it can be saved later on fileFromZip.Read(buffer1, 0, buffer1.Length); } countZip++; if (countZip % 50 == 0) { LoaderProgress(3); } } } } Deployment.Current.Dispatcher.BeginInvoke(() => { statPageLoaded = true; myWB.Base = "wp8"; myWB.Navigate(new Uri("engine_wp8_nativ.html", UriKind.Relative)); }); }
public Task CreateDirectoryAsync(string path) { isolatedStorageFile.CreateDirectory(path); return(Task.FromResult(true)); }
public void uncompress(string options) { // bring options Debug.WriteLine("raw options for uncompress: " + options); ZipOptions zipOptions = JSON.JsonHelper.Deserialize <ZipOptions>(options); Debug.WriteLine("selected source for uncompress:" + zipOptions.source); Debug.WriteLine("selected target for uncompress:" + zipOptions.target); // prepare file handlers for SL 4 IsolatedStorageFile infile = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFile outfile = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFile path = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFile directory = IsolatedStorageFile.GetUserStoreForApplication(); // direct access to targetPath string targetPath = zipOptions.target; string lastMsg; // get total of entries long count = 0; count = this.getTotalOfEntries(zipOptions.source); // open zip file using (ZipInputStream decompressor = new ZipInputStream(infile.OpenFile(zipOptions.source, FileMode.Open))) { ZipEntry entry; // iterate through entries of the zip file while ((entry = decompressor.GetNextEntry()) != null) { string filePath = Path.Combine(targetPath, entry.Name); string directoryPath = Path.GetDirectoryName(filePath); // create directory if not exists if (!string.IsNullOrEmpty(directoryPath) && !directory.FileExists(directoryPath)) { directory.CreateDirectory(directoryPath); } this.processedEntities.Add(filePath); // don't consume cycles to write files if it's a directory if (entry.IsDirectory) { continue; } // unzip and create file byte[] data = new byte[2048]; using (FileStream streamWriter = outfile.CreateFile(filePath)) { int bytesRead; while ((bytesRead = decompressor.Read(data, 0, data.Length)) > 0) { streamWriter.Write(data, 0, bytesRead); } } lastMsg = this.publish(filePath, count); } } }