private void GetPrintersButton_Click(object sender, RoutedEventArgs e) { WebClient a = new WebClient(); a.OpenReadAsync(new Uri(ScriptFileNameString, UriKind.Relative)); a.OpenReadCompleted += (object sender1, OpenReadCompletedEventArgs e1) => { StreamReader reader = new StreamReader(e1.Result); string VBSContents = reader.ReadToEnd(); reader.Close(); if (AutomationFactory.IsAvailable) { // Interesting, I can simply try to dispose a dynamic object without checking whether it has implemented IDisposible:) using (dynamic fso = AutomationFactory.CreateObject("Scripting.FileSystemObject")) { if (!fso.FolderExists(TempFolderPathString)) { fso.CreateFolder(TempFolderPathString); } dynamic txtFile = fso.CreateTextFile(TempFolderPathString + ScriptFileNameString); txtFile.WriteLine(VBSContents); txtFile.close(); } } dynamic shell = AutomationFactory.CreateObject("Shell.Application"); shell.ShellExecute(TempFolderPathString + ScriptFileNameString, "", "", "open", 1); if (AutomationFactory.IsAvailable) { var fileContent = String.Empty; using (dynamic fso = AutomationFactory.CreateObject("Scripting.FileSystemObject")) { dynamic file = fso.OpenTextFile(TempFolderPathString + OutputFileNameString, 1, -1); while (!file.AtEndOfStream) { fileContent = fileContent + file.ReadLine() + ","; } file.Close(); } if (fileContent != "") { fileContent = fileContent.Substring(0, fileContent.Length - 1); } using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForSite()) { if (isf.FileExists(OutputFileNameString)) { isf.DeleteFile(OutputFileNameString); } using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(OutputFileNameString, FileMode.OpenOrCreate, isf)) { using (StreamWriter sw = new StreamWriter(isfs)) { sw.Write(fileContent); sw.Close(); } } string[] str = fileContent.Split(','); ListOfPrintersComboBox.IsEnabled = true; foreach (var item in str) { ListOfPrintersComboBox.Items.Add(item); } if (ListOfPrintersComboBox.Items.Count > 0) { ListOfPrintersComboBox.SelectedIndex = 0; } } } }; PrintPDFButton.IsEnabled = true; }
public static async void Reminder() { //Update License (eg. If someone bought the app) SetLicense(); //Set ApplicationTitle if (GTaskSettings.IsFree) { GTaskSettings.ApplicationTitle = "GTask"; } else { GTaskSettings.ApplicationTitle = "GTask+"; } //New Feature Popup (increment 1 each time you want it to show up) int NumFeature = 9; if (GTaskSettings.NewFeatureCount < NumFeature) { MessageBox.Show("- Offline Mode \r\n- Speech-to-Text \r\n- New Icons \r\n- Auto-Sync\r\n- More Customizations in Settings", "New Features!", MessageBoxButton.OK); if (GTaskSettings.IsFree) { MessageBox.Show("To get the latest data from Google use the 'Sync' button.\r\n \r\nYou can enable Auto-Sync by upgrading to the Paid version\r\n \r\nSend me any questions, feedback, or issues:\r\n - Tweet @MattLoflin\r\n - [email protected]", "Instructions", MessageBoxButton.OK); } else { MessageBox.Show("To get the latest data from Google use the 'Sync' button OR enable Auto-Sync in settings.\r\n \r\nSend me any questions, feedback, or issues:\r\n - Tweet @MattLoflin\r\n - [email protected]", "Instructions", MessageBoxButton.OK); } //due to possible data issues with localization changes - force update of Google data //Remove LocalStorage (if exists) string ApplicationDataFileName = "TaskListData.txt"; IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); if (storage.FileExists(ApplicationDataFileName)) { storage.DeleteFile(ApplicationDataFileName); } //Set First run to true for forced sync GTaskSettings.FirstRun = true; if (GTaskSettings.IsFree) //if free then turn off 'auto' features { GTaskSettings.AutoClear = false; GTaskSettings.AutoRefreshLists = false; GTaskSettings.AutoRefreshTasks = false; } //If the user already installed the app and HideCompleted = true then remove hidden to speed up processing //localStorageList should be null if not used yet List <Model.TaskListItem> localStorageList = await TaskListHelper.GetTaskListFromApplicationStorage(false); if (GTaskSettings.HideCompleted == true && (localStorageList != null || localStorageList.Count == 0)) { bool results = await GTaskSettings.RemoveHidden(); } //Check for pinned lists - if pinned then prompt user to re-pin bool pinned = false; foreach (ShellTile shellTile in ShellTile.ActiveTiles) { try { if (shellTile.NavigationUri.ToString().Contains("/Views/TaskView.xaml?Id=")) { pinned = true; } } catch (Exception)// e) { } } if (pinned) { MessageBox.Show("I noticed that you have Task List(s) pinned to the Start Screen.\r\n \r\nPlease Re-pin any Task List(s) to enable updated features.", "Action Required", MessageBoxButton.OK); } //update NewFeatureCount to latest so user doesn't see this again GTaskSettings.NewFeatureCount = NumFeature; } //Only try to do one popup per session - if the new feature popup isn't being used, then do others (if applicable) else { // //##RATE ME POPUP## // int daysElapsed = (int)(DateTime.Now.Subtract(GTaskSettings.ReminderDate).TotalDays); if (daysElapsed > 7 && !GTaskSettings.Rated) { MessageBoxResult m = MessageBox.Show("Hey! I see you have been using the app for a while now, could you click 'OK' to Rate it or Send me feedback through 'Settings'->'About'?", "Feedback?", MessageBoxButton.OKCancel); if (m == MessageBoxResult.OK) { //Navigate to Rating Page MarketplaceReviewTask oRateTask = new MarketplaceReviewTask(); oRateTask.Show(); //Set Rated = True (assuming they rated by clicking OK) GTaskSettings.Rated = true; } else { //Set Reminder Date to Today to remind again in 7 days GTaskSettings.ReminderDate = DateTime.Now; } } } //If this was added after someone logged it, the value wouldn't be set until they login again //Given the default return is MaxValue - we can catch it and reset it to Today's date if (GTaskSettings.ReminderDate == DateTime.MaxValue) { GTaskSettings.ReminderDate = DateTime.Now; } }
public bool Activate(bool instancePreserved) { #if !WINDOWS_PHONE return(false); #else // If the game instance was preserved, the game wasn't dehydrated so our screens still exist. // We just need to activate them and we're ready to go. if (instancePreserved) { // Make a copy of the master screen list, to avoid confusion if // the process of activating one screen adds or removes others. tempScreensList.Clear(); foreach (GameScreen screen in screens) { tempScreensList.Add(screen); } foreach (GameScreen screen in tempScreensList) { screen.Activate(true); } } // Otherwise we need to refer to our saved file and reconstruct the screens that were present // when the game was deactivated. else { // Try to get the screen factory from the services, which is required to recreate the screens IScreenFactory screenFactory = Game.Services.GetService(typeof(IScreenFactory)) as IScreenFactory; if (screenFactory == null) { throw new InvalidOperationException( "Game.Services must contain an IScreenFactory in order to activate the ScreenManager."); } // Open up isolated storage using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { // Check for the file; if it doesn't exist we can't restore state if (!storage.FileExists(StateFilename)) { return(false); } // Read the state file so we can build up our screens using (IsolatedStorageFileStream stream = storage.OpenFile(StateFilename, FileMode.Open)) { XDocument doc = XDocument.Load(stream); // Iterate the document to recreate the screen stack foreach (XElement screenElem in doc.Root.Elements("GameScreen")) { // Use the factory to create the screen Type screenType = Type.GetType(screenElem.Attribute("Type").Value); GameScreen screen = screenFactory.CreateScreen(screenType); // Rehydrate the controlling player for the screen PlayerIndex?controllingPlayer = screenElem.Attribute("ControllingPlayer").Value != "" ? (PlayerIndex)Enum.Parse(typeof(PlayerIndex), screenElem.Attribute("ControllingPlayer").Value, true) : (PlayerIndex?)null; screen.ControllingPlayer = controllingPlayer; // Add the screen to the screens list and activate the screen screen.ScreenManager = this; screens.Add(screen); screen.Activate(false); // update the TouchPanel to respond to gestures this screen is interested in TouchPanel.EnabledGestures = screen.EnabledGestures; } } } } return(true); #endif }
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 ConnectPage() { InitializeComponent(); // Sauvegarde de l'avatar dans la mémoire du téléphone _webClient = new WebClient(); _webClient.OpenReadCompleted += (s1, e1) => { if (e1.Error == null) { try { string fileName = store["userAvatarFile"] as string; bool isSpaceAvailable = IsSpaceIsAvailable(e1.Result.Length); if (isSpaceAvailable) { if (isoStore.FileExists(fileName)) { isoStore.DeleteFile(fileName); } using (var isfs = new IsolatedStorageFileStream(fileName, FileMode.CreateNew, isoStore)) { long fileLen = e1.Result.Length; byte[] b = new byte[fileLen]; e1.Result.Read(b, 0, b.Length); if (b[0] == 71 && b[1] == 73 && b[2] == 70) { // File is a GIF, we need to convert it! var image = new ExtendedImage(); var gifDecoder = new ImageTools.IO.Gif.GifDecoder(); gifDecoder.Decode(image, new MemoryStream(b)); image.WriteToStream(isfs, "avatar.png"); Dispatcher.BeginInvoke(() => { store.Remove("isConnected"); store.Add("isConnected", ""); NavigationService.Navigate(new Uri("/WelcomePage.xaml?from=connect", UriKind.Relative)); }); } else { isfs.Write(b, 0, b.Length); isfs.Flush(); Dispatcher.BeginInvoke(() => { store.Remove("isConnected"); store.Add("isConnected", ""); NavigationService.Navigate(new Uri("/WelcomePage.xaml?from=connect", UriKind.Relative)); }); } } } else { Dispatcher.BeginInvoke(() => { MessageBox.Show("Erreur lors de la première connexion. La mémoire de votre terminal semble pleine."); }); } } catch (Exception ex) { Dispatcher.BeginInvoke(() => { MessageBox.Show("Erreur n°1 dans la sauvegarde de l'avatar : " + ex.Message); }); } } else { Dispatcher.BeginInvoke(() => { MessageBox.Show("Erreur n°2 dans la sauvegarde de l'avatar : " + e1.Error.Message); }); } }; }
public static bool LocalFileExists(string fileName) { IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication(); return(myIsolatedStorage.FileExists(fileName)); }
/// <summary> /// Determines whether the specified path refers to an existing file in the store. /// </summary> /// <param name="path">The path and file name to test.</param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public Task <bool> FileExistsAsync(string path) { return(Task.Factory.StartNew(() => Storage.FileExists(path))); }
public 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()) { // 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 string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", ""); 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; 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> /// /// </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 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 bool DeserializeState() { try { // open up isolated storage using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { // see if our saved state directory exists if (storage.DirectoryExists(m_sStorageDirName)) { string saveFile = System.IO.Path.Combine(m_sStorageDirName, m_sSaveFileName); try { CCLog.Log("Loading director data file: {0}", saveFile); // see if we have a screen list if (storage.FileExists(saveFile)) { // load the list of screen types using (IsolatedStorageFileStream stream = storage.OpenFile(saveFile, FileMode.Open, FileAccess.Read)) { using (StreamReader reader = new StreamReader(stream)) { CCLog.Log("Director save file contains {0} bytes.", reader.BaseStream.Length); try { while (true) { // read a line from our file string line = reader.ReadLine(); if (line == null) { break; } CCLog.Log("Restoring: {0}", line); // if it isn't blank, we can create a screen from it if (!string.IsNullOrEmpty(line)) { if (line.StartsWith("[*]")) { // Reading my state string s = line.Substring(3); int idx = s.IndexOf('='); if (idx > -1) { string name = s.Substring(0, idx); string v = s.Substring(idx + 1); CCLog.Log("Restoring: {0} = {1}", name, v); DeserializeMyState(name, v); } } else { Type screenType = Type.GetType(line); CCScene scene = Activator.CreateInstance(screenType) as CCScene; PushScene(scene); // m_pobScenesStack.Add(scene); } } } } catch (Exception) { // EndOfStreamException // this is OK here. } } } // Now we deserialize our own state. } else { CCLog.Log("save file does not exist."); } // next we give each screen a chance to deserialize from the disk for (int i = 0; i < m_pobScenesStack.Count; i++) { string filename = System.IO.Path.Combine(m_sStorageDirName, string.Format(m_sSceneSaveFileName, i)); if (storage.FileExists(filename)) { using (IsolatedStorageFileStream stream = storage.OpenFile(filename, FileMode.Open, FileAccess.Read)) { CCLog.Log("Restoring state for scene {0}", filename); m_pobScenesStack[i].Deserialize(stream); } } } if (m_pobScenesStack.Count > 0) { CCLog.Log("Director is running with scene.."); RunWithScene(m_pobScenesStack[m_pobScenesStack.Count - 1]); // always at the top of the stack } return(m_pobScenesStack.Count > 0 && m_pRunningScene != null); } catch (Exception ex) { // if an exception was thrown while reading, odds are we cannot recover // from the saved state, so we will delete it so the game can correctly // launch. DeleteState(storage); CCLog.Log("Failed to deserialize the director state, removing old storage file."); CCLog.Log(ex.ToString()); } } } } catch (Exception ex) { CCLog.Log("Failed to deserialize director state."); CCLog.Log(ex.ToString()); } return(false); }
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); } } }
private void readObject() { string filePath = HikeConstants.ANALYTICS_OBJECT_DIRECTORY + "/" + HikeConstants.ANALYTICS_OBJECT_FILE; using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) // grab the storage { if (!store.DirectoryExists(HikeConstants.ANALYTICS_OBJECT_DIRECTORY) || !store.FileExists(filePath)) { return; } using (var file = store.OpenFile(filePath, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(file)) { this.Read(reader); } } } }
public IEnumerable <TvDbSeries> GetSavedSeries() { using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { var dirs = storage.GetDirectoryNames(string.Format(@"{0}\*", SubscriptionsFolderName)); if (dirs.Length > 0) { foreach (var dir in dirs) { var filename = string.Format(@"{0}\{1}\data.xml", SubscriptionsFolderName, dir); TvDbSeries series; using (new MutexLock(filename)) { if (!storage.FileExists(filename)) { continue; } try { using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, storage)) { if (stream.Length == 0) { continue; } series = (TvDbSeries)Serializer.Deserialize(stream); var seenFilename = string.Format(@"{0}\{1}\seen.xml", SubscriptionsFolderName, series.Id); using (new MutexLock(seenFilename)) { if (storage.FileExists(seenFilename)) { using (var seenStream = new IsolatedStorageFileStream(seenFilename, FileMode.Open, storage)) { var seen = (List <string>)SeenSerializer.Deserialize(seenStream); foreach (var episodeId in seen) { var episode = series.Episodes.FirstOrDefault(e => e.Id.Equals(episodeId)); if (episode != null) { episode.IsSeen = true; } } } storage.DeleteFile(seenFilename); } } } } catch (InvalidOperationException) { try { storage.DeleteFile(filename); } catch { } OnStorageFailure( new StorageFailureEventArgs( "Error loading series from phone storage. Part of your data will be lost. Very sorry :(")); continue; } } yield return(series); } } } }
void prompt_Completed(object sender, PopUpEventArgs <string, PopUpResult> e) { if (e.PopUpResult == PopUpResult.Ok) { if (!string.IsNullOrEmpty(e.Result)) { string testFileName = e.Result + ".mp3"; if (IsValidFilename(testFileName)) { try { using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication()) { if (!file.DirectoryExists("Music")) { file.CreateDirectory("Music"); } if (!file.FileExists("/Music/" + testFileName)) { WriteFile(testFileName, file); } else { if (MessageBox.Show("File already exists. Overwrite?", "Beem", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { WriteFile(testFileName, file); } else { DisplaySavePrompt(); } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); MessageBox.Show("For some reason, Beem cannot save this file. Check the amount of available space.", "Beem", MessageBoxButton.OK); } } else { Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show("File name contains invalid characters.", "Beem", MessageBoxButton.OK); }); } } else { Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show("You nee to specify a file name to save this recording.", "Beem", MessageBoxButton.OK); }); } } PlaybackPageViewModel.Instance.RecordingLength = 0; }
//Bilder löschen private void BtnDelete(object sender, EventArgs e) { //Prüfen ob Multiselect aktiviert ist if (LBImages.SelectionMode == SelectionMode.Multiple) { //Prüfen wieviele Bilder ausgewählt sind ImagesToDelete_c = LBImages.SelectedItems.Count; //Prüfen ob Bilder ausgewählt sind und löschen if (ImagesToDelete_c > 0) { //Warnung ausgeben if (MessageBox.Show(Lockscreen_Swap.AppResx.DeleteImages, Lockscreen_Swap.AppResx.Warning, MessageBoxButton.OKCancel) == MessageBoxResult.OK) { //ImagesToDelete Liste erstellen ImagesToDelete = new string[ImagesToDelete_c]; //IO File erstellen IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication(); //Ausgewählte Bilder durchlaufen for (int i = 0; i < ImagesToDelete_c; i++) { //Bilder löschen if (file.FileExists((LBImages.SelectedItems[i] as ClassPictures).imgPath)) { file.DeleteFile((LBImages.SelectedItems[i] as ClassPictures).imgPath); } //Thumbnail löschen if (file.FileExists((LBImages.SelectedItems[i] as ClassPictures).imgThumbPath)) { file.DeleteFile((LBImages.SelectedItems[i] as ClassPictures).imgThumbPath); } //ImagesAll bearbeiten ImagesAll = ImagesAll.Replace("/" + (LBImages.SelectedItems[i] as ClassPictures).imgFile + "/", "/"); //Image.dat neu erstellen IsolatedStorageFileStream filestream = file.CreateFile("/Thumbs/" + Folder + ".dat"); StreamWriter sw = new StreamWriter(filestream); sw.WriteLine(ImagesAll); sw.Flush(); filestream.Close(); } //ImgSelectSave auf false stellen ImgSelectSave = false; //Listbox auswahl aufheben try { LBImages.SelectedIndex = -1; } catch { } //Bilderliste neu erstellen CreateImages(); //ImgSelectSave auf true stellen ImgSelectSave = true; } } //Wenn keine Bilder ausgewählt sind, Warnung ausgeben else { //Warnung ausgeben MessageBox.Show(Lockscreen_Swap.AppResx.SelectDelete); } } }
/// <summary> /// Read file from Isolated Storage and sends it to server /// </summary> /// <param name="asynchronousResult"></param> private void uploadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; HttpWebRequest webRequest = reqState.request; string callbackId = reqState.options.CallbackId; try { using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult))) { string lineStart = "--"; string lineEnd = Environment.NewLine; byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd; if (!string.IsNullOrEmpty(reqState.options.Params)) { Dictionary <string, string> paramMap = parseHeaders(reqState.options.Params); foreach (string key in paramMap.Keys) { requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); string formItem = string.Format(formdataTemplate, key, paramMap[key]); byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem); requestStream.Write(formItemBytes, 0, formItemBytes.Length); } requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(reqState.options.FilePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0))); return; } byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd); long totalBytesToSend = 0; using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile)) { string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd; string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType); byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header); byte[] buffer = new byte[4096]; int bytesRead = 0; totalBytesToSend = fileStream.Length; requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); requestStream.Write(headerBytes, 0, headerBytes.Length); while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { if (!reqState.isCancelled) { requestStream.Write(buffer, 0, bytesRead); bytesSent += bytesRead; DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId); System.Threading.Thread.Sleep(1); } else { throw new Exception("UploadCancelledException"); } } } requestStream.Write(endRequest, 0, endRequest.Length); } } // webRequest webRequest.BeginGetResponse(ReadCallback, reqState); } catch (Exception /*ex*/) { if (!reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); } } }
//--------------------------------------------------------------------------------------------------------------------------------- //Ordner auswählen //Kopieren //--------------------------------------------------------------------------------------------------------------------------------- private void SelectFolder(object sender, SelectionChangedEventArgs e) { //Ordner Pfad laden string TargetPath = "/Folders/" + (datalist2[LBFolders.SelectedIndex] as ClassFolders).name + "/"; string TargetThumbPath = "/Thumbs/" + (datalist2[LBFolders.SelectedIndex] as ClassFolders).name + "/"; //Wenn Quelle anders als ziel if ((datalist2[LBFolders.SelectedIndex] as ClassFolders).name != Folder) { if (MessageBox.Show(Lockscreen_Swap.AppResx.CopyImagesTo + "\n" + (datalist2[LBFolders.SelectedIndex] as ClassFolders).name, Lockscreen_Swap.AppResx.Notification, MessageBoxButton.OKCancel) == MessageBoxResult.OK) { //Images.dat laden //Zu kopierender Ordner IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream filestream = file.OpenFile("Thumbs/" + (datalist2[LBFolders.SelectedIndex] as ClassFolders).name + ".dat", FileMode.Open); StreamReader sr = new StreamReader(filestream); string ImagesAll2 = sr.ReadToEnd(); filestream.Close(); ImagesAll2 = ImagesAll2.TrimEnd(new char[] { '\r', '\n' }); //ImagesToCopy Liste erstellen ImagesToCopy = new string[ImagesToCopy_c]; //Ausgewählte Bilder durchlaufen for (int i = 0; i < ImagesToCopy_c; i++) { //Bilder kopieren IsolatedStorageFile file02 = IsolatedStorageFile.GetUserStoreForApplication(); if (!file02.FileExists(TargetPath + (LBImages.SelectedItems[i] as ClassPictures).imgFile)) { file02.CopyFile(((LBImages.SelectedItems[i] as ClassPictures).imgPath), TargetPath + (LBImages.SelectedItems[i] as ClassPictures).imgFile); } if (!file02.FileExists(TargetThumbPath + (LBImages.SelectedItems[i] as ClassPictures).imgFile)) { file02.CopyFile(((LBImages.SelectedItems[i] as ClassPictures).imgThumbPath), TargetThumbPath + (LBImages.SelectedItems[i] as ClassPictures).imgFile); } //ImagesAll Zu kopierender Ordner ändern ImagesAll2 += (LBImages.SelectedItems[i] as ClassPictures).imgFile + "/"; //Images.dat //Zu kopierender ordner filestream = file.CreateFile("Thumbs/" + (datalist2[LBFolders.SelectedIndex] as ClassFolders).name + ".dat"); StreamWriter sw = new StreamWriter(filestream); sw.WriteLine(ImagesAll2); sw.Flush(); filestream.Close(); } //Auswahl aufheben try { LBFolders.SelectedIndex = -1; } catch { } //Copy zurücksetzen CopyRoot.Margin = new Thickness(-600, 0, 0, 0); //MenuOpene zurücksetzen MenuOpen = false; } //Bei Abbruch else { //Auswahl aufheben try { LBFolders.SelectedIndex = -1; } catch { } } } //Wenn Quelle gleich Ziel else { //Auswahl aufheben try { LBFolders.SelectedIndex = -1; } catch { } //Nachricht ausgeben MessageBox.Show(Lockscreen_Swap.AppResx.SourceTarget); } }
public static bool Exists(string file) { IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication(); return(storageFile.FileExists(file)); }
private void SetLockscreenImage(ScheduledTask task, LockscreenData data) { try { bool isProvider = LockScreenManager.IsProvidedByCurrentApplication; if (isProvider) { int itemCount = data.Items == null ? 0 : data.Items.Length; //1. 이번에 변경할 파일을 알아야 한다. 그러기 위해서 먼저 현재 락스크린 파일명을 구한다. Uri lockscreenFileUri = null; string lockscreenFileName = null; try { lockscreenFileUri = LockScreen.GetImageUri(); } catch (Exception) { ShellToast toast = new ShellToast(); toast.Title = AppResources.ApplicationTitle; toast.Content = AppResources.MsgFailShortGetLockscreen; toast.Show(); return; } if (lockscreenFileUri != null) { lockscreenFileName = lockscreenFileUri.ToString() .Replace(Constants.PREFIX_APP_DATA_FOLDER, string.Empty) .Replace(Constants.LOCKSCREEN_IMAGE_A_POSTFIX, Constants.LOCKSCREEN_IMAGE_POSTFIX) .Replace(Constants.LOCKSCREEN_IMAGE_B_POSTFIX, Constants.LOCKSCREEN_IMAGE_POSTFIX); } //2. 이번에 변경할 파일명을 구한다. using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (!string.IsNullOrEmpty(lockscreenFileName)) { lockscreenFileName = lockscreenFileName.Replace(Constants.LOCKSCREEN_IMAGE_POSTFIX, Constants.LOCKSCREEN_IMAGE_READY_POSTFIX); } var imgNames = from element in isoStore.GetFileNames() where element.Contains(Constants.LOCKSCREEN_IMAGE_READY_POSTFIX) && element.CompareTo(lockscreenFileName) > 0 orderby element ascending select element; //이번에 업데이트 할 이미지 이름을 임시 저장 lockscreenFileName = imgNames.Any() ? imgNames.First() : isoStore.GetFileNames(string.Format("*{0}", Constants.LOCKSCREEN_IMAGE_READY_POSTFIX))[0]; using (IsolatedStorageFileStream sourceStream = isoStore.OpenFile(lockscreenFileName, FileMode.Open, FileAccess.Read)) { data.BackgroundBitmap = BitmapFactory.New(0, 0).FromStream(sourceStream); } //3. 표시할 아이템들과 이미지를 합성한다. (이미지 리사이징 포함) LockscreenHelper.RenderLayoutToBitmap(data); GC.Collect(); System.Threading.Thread.Sleep(1500); System.Diagnostics.Debug.WriteLine("이미지 생성 직후" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage); //4. 새로운 이름으로 저장하기 위해 전환 논리를 이용하여 새로운 이름을 구한다. if (lockscreenFileUri != null && lockscreenFileUri.ToString().EndsWith(Constants.LOCKSCREEN_IMAGE_A_POSTFIX)) { lockscreenFileName = lockscreenFileName.Replace(Constants.LOCKSCREEN_IMAGE_READY_POSTFIX, Constants.LOCKSCREEN_IMAGE_B_POSTFIX); } else { lockscreenFileName = lockscreenFileName.Replace(Constants.LOCKSCREEN_IMAGE_READY_POSTFIX, Constants.LOCKSCREEN_IMAGE_A_POSTFIX); } //5. 새로운 이름으로 이미지를 저장 using (IsolatedStorageFileStream targetStream = isoStore.OpenFile(lockscreenFileName, FileMode.Create, FileAccess.Write)) { data.BackgroundBitmap.SaveJpeg(targetStream, data.BackgroundBitmap.PixelWidth, data.BackgroundBitmap.PixelHeight, 0, 100); //using (MemoryStream ms = new MemoryStream()) //{ // data.BackgroundBitmap.SaveJpeg(ms, data.BackgroundBitmap.PixelWidth, data.BackgroundBitmap.PixelHeight, 0, 100); // System.Diagnostics.Debug.WriteLine("{0}x{1}", data.BackgroundBitmap.PixelWidth, data.BackgroundBitmap.PixelHeight); // byte[] readBuffer = new byte[4096]; // int bytesRead = -1; // ms.Position = 0; // targetStream.Position = 0; // while ((bytesRead = ms.Read(readBuffer, 0, readBuffer.Length)) > 0) // { // targetStream.Write(readBuffer, 0, bytesRead); // } //} } //6. 새로운 이미지로 락스크린 업데이트 LockScreen.SetImageUri(new Uri(string.Format("{0}{1}", Constants.PREFIX_APP_DATA_FOLDER, lockscreenFileName), UriKind.Absolute)); Uri newLockscreenFileUri = LockScreen.GetImageUri(); //7.변경이 정상적으로 이루어진 경우 기존 파일 삭제 if (newLockscreenFileUri.ToString() != lockscreenFileUri.ToString()) { if (lockscreenFileUri.ToString().Contains(Constants.PREFIX_APP_DATA_FOLDER)) { lockscreenFileName = lockscreenFileUri.ToString().Replace(Constants.PREFIX_APP_DATA_FOLDER, string.Empty); if (isoStore.FileExists(lockscreenFileName)) { isoStore.DeleteFile(lockscreenFileName); } } } } } } catch (Exception e) { LoggingError("error case 3 : \n" + e.StackTrace); } // If debugging is enabled, launch the agent again in one minute. #if DEBUG_AGENT ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30)); System.Diagnostics.Debug.WriteLine(Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage); /* * ShellToast toast = new ShellToast(); * toast.Title = AppResources.ApplicationTitle; * toast.Content = AppResources.MsgSuccessChangeLockscreen; * toast.Show(); */ #else IsolatedStorageSettings.ApplicationSettings[Constants.LAST_RUN_LOCKSCREEN] = DateTime.Now; IsolatedStorageSettings.ApplicationSettings.Save(); #endif }
/// <summary> /// 判定指定的IsolatedStorage文件是否存在 /// </summary> /// /// <param name="resName"></param> /// <returns></returns> public static bool ExistsIsolatedStorage(string resName) { IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication(); return(isoStorage.FileExists(resName)); }
/// <summary> /// Updates the state of the game. This method checks the GameScreen.IsActive /// property, so the game will stop updating when the pause menu is active, /// or if you tab away to a different application. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, false); SpriteBatch spriteBatch = ScreenManager.SpriteBatch; // Gradually fade in or out depending on whether we are covered by the pause screen. if (coveredByOtherScreen) { pauseAlpha = Math.Min(pauseAlpha + 1f / 32, 1); } else { pauseAlpha = Math.Max(pauseAlpha - 1f / 32, 0); } if (IsActive) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { ScreenManager.AddScreen(new PhonePauseScreen(), ControllingPlayer); } TouchCollection touches = TouchPanel.GetState(); if (!bTouching && touches.Count > 0) { bTouching = true; TouchLocation touch = touches[0]; if (boardHandler.MenuPressed(touch, spriteBatch)) { ScreenManager.AddScreen(new PhonePauseScreen(), ControllingPlayer); } else { if (!boardHandler.InProgress) { boardHandler.Touch(touch, spriteBatch); } } } else if (touches.Count == 0) { bTouching = false; } if (boardHandler.InProgress && !boardHandler.Rotating()) { boardHandler.CauseChainReaction(); } else { if (boardHandler.GetScore == boardHandler.GetTargetScore) { //Add save score here string saveString = string.Format("{0},{1},{2}{3}", boardHandler.GetScore, boardHandler.Attempts, DateTime.Now.ToString(), Environment.NewLine); // Open a storage container. try { IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); // grab the storage FileStream stream; if (!store.FileExists(HIGHSCORE_FILE)) { stream = store.CreateFile(HIGHSCORE_FILE); } else { stream = store.OpenFile(HIGHSCORE_FILE, FileMode.Append); } StreamWriter writer = new StreamWriter(stream); writer.Write(saveString); writer.Close(); } catch (Exception ex) { } ScreenManager.AddScreen(new FinishGameScreen(boardHandler.GetScore, boardHandler.Attempts), ControllingPlayer); } } } }
public static bool FileExists(string fileName) { return(_store.FileExists(fileName)); }
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(); }
private void DownloadFavPage() { try { string urlFav = "https://forum.hardware.fr/forum1f.php?owntopic=" + (string)store["favorisType"]; HtmlWeb.LoadAsync(urlFav, container as CookieContainer, (s, args) => { if (args.Error != null) { TileErreur(); } else { try { int i = 0; string[] favorisTopicNames = args.Document.DocumentNode.Descendants("a").Where(x => (string)x.GetAttributeValue("class", "") == "cCatTopic" && (bool)x.GetAttributeValue("title", "").Contains("Sujet") == true). Select(y => y.InnerText).ToArray(); string[] favorisTopicNumberOfPages = args.Document.DocumentNode.Descendants("td").Where(x => (string)x.GetAttributeValue("class", "") == "sujetCase4"). Select(y => y.InnerText).ToArray(); string[] favorisTopicUri = args.Document.DocumentNode.Descendants("a").Where(x => (string)x.GetAttributeValue("class", "") == "cCatTopic" && (bool)x.GetAttributeValue("title", "").Contains("Sujet") == true). Select(y => y.GetAttributeValue("href", "")).ToArray(); string[] favorisLastPost = args.Document.DocumentNode.Descendants("td").Where(x => (bool)x.GetAttributeValue("class", "").Contains("sujetCase9") == true). Select(y => y.InnerText).ToArray(); string[] favorisIsHot = args.Document.DocumentNode.Descendants("img").Where(x => (string)x.GetAttributeValue("alt", "") == "Off" || (string)x.GetAttributeValue("alt", "") == "On"). Select(y => y.GetAttributeValue("alt", "")).ToArray(); string[] favorisBalise = args.Document.DocumentNode.Descendants("a").Where(x => (bool)x.GetAttributeValue("href", "").Contains("#t")). Select(y => y.GetAttributeValue("href", "")).ToArray(); string[] mpArray = args.Document.DocumentNode.Descendants("a").Where(x => (string)x.GetAttributeValue("class", "") == "red"). Select(y => y.InnerText).ToArray(); string numberOfPagesTopicLine = ""; int j = 0; foreach (string line in favorisTopicNames) { if (favorisIsHot[i] == "On") { // Nombre de pages if (favorisTopicNumberOfPages[i] != " ") { numberOfPagesTopicLine = favorisTopicNumberOfPages[i]; } else { numberOfPagesTopicLine = "1"; } string topicCatId; int firstTopicCatId = HttpUtility.HtmlDecode(favorisBalise[j]).IndexOf("&cat=") + "&cat=".Length; int lastTopicCatId = HttpUtility.HtmlDecode(favorisBalise[j]).IndexOf("&", firstTopicCatId); topicCatId = HttpUtility.HtmlDecode(favorisBalise[j]).Substring(firstTopicCatId, lastTopicCatId - firstTopicCatId); string topicId; int firstTopicId = HttpUtility.HtmlDecode(favorisBalise[j]).IndexOf("&post=") + "&post=".Length; int lastTopicId = HttpUtility.HtmlDecode(favorisBalise[j]).LastIndexOf("&page"); topicId = HttpUtility.HtmlDecode(favorisBalise[j]).Substring(firstTopicId, lastTopicId - firstTopicId); string reponseId; int firstReponseId = HttpUtility.HtmlDecode(favorisBalise[j]).IndexOf("#t") + "#t".Length; int lastReponseId = HttpUtility.HtmlDecode(favorisBalise[j]).Length; reponseId = "rep" + HttpUtility.HtmlDecode(favorisBalise[j]).Substring(firstReponseId, lastReponseId - firstReponseId); string pageNumber; int firstPageNumber = HttpUtility.HtmlDecode(favorisBalise[j]).IndexOf("&page=") + "&page=".Length; int lastPageNumber = HttpUtility.HtmlDecode(favorisBalise[j]).LastIndexOf("&p="); pageNumber = HttpUtility.HtmlDecode(favorisBalise[j]).Substring(firstPageNumber, lastPageNumber - firstPageNumber); // Formatage topic name string topicNameFav; topicNameFav = Regex.Replace(HttpUtility.HtmlDecode(line), "topic unique", "T.U.", RegexOptions.IgnoreCase); topicNameFav = Regex.Replace(HttpUtility.HtmlDecode(line), "topique unique", "T.U.", RegexOptions.IgnoreCase); topicNameFav = Regex.Replace(topicNameFav, "topic unik", "T.U.", RegexOptions.IgnoreCase); topicNameFav = Regex.Replace(topicNameFav, "topik unik", "T.U.", RegexOptions.IgnoreCase); // Conversion date string favorisSingleLastPostTimeString; favorisSingleLastPostTimeString = Regex.Replace(Regex.Replace(HttpUtility.HtmlDecode(favorisLastPost[i].Substring(0, 28)), "à", ""), "-", "/"); DateTime favorisSingleLastPostDT; favorisSingleLastPostDT = DateTime.Parse(favorisSingleLastPostTimeString, new CultureInfo("fr-FR")); double favorisSingleLastPostTime; favorisSingleLastPostTime = Convert.ToDouble(favorisSingleLastPostDT.ToFileTime()); // Nom du dernier posteur string favorisLastPostUser; favorisLastPostUser = HttpUtility.HtmlDecode(favorisLastPost[i].Substring(28, favorisLastPost[i].Length - 28)); // Temps depuis dernier post string favorisLastPostText; TimeSpan timeSpent; timeSpent = DateTime.Now.Subtract(favorisSingleLastPostDT); favorisLastPostText = HFR7.HFRClasses.TimeSpentTopic.Run(timeSpent, favorisLastPostUser); favObject.Add(new HFR7.HFRClasses.TopicFav() { TopicNameFav = topicNameFav, TopicCatIdFav = topicCatId, TopicIdFav = topicId, TopicCatNameFav = HFR7.HFRClasses.GetCatName.PlainNameFromId(topicCatId), TopicUriFav = "?idcat=" + topicCatId + "&idtopic=" + topicId + "&topicname=" + HttpUtility.UrlEncode(line) + "&pagenumber=" + pageNumber + "&jump=" + reponseId + "&numberofpages=" + numberOfPagesTopicLine, TopicLastPostDateDouble = favorisSingleLastPostTime, TopicLastPost = favorisLastPostText, TopicNumberOfPages = numberOfPagesTopicLine, TopicPage = pageNumber, TopicJump = reponseId }); j++; } i++; } //////////////////////////////// // Mise à jour des tiles topics //////////////////////////////// foreach (ShellTile tile in ShellTile.ActiveTiles) { bool containsFav = false; if (tile.NavigationUri.ToString() != "/") { string tilePostId; int firstTilePostId = HttpUtility.HtmlDecode(tile.NavigationUri.ToString()).IndexOf("&idtopic=") + "&idtopic=".Length; int lastTilePostId = HttpUtility.HtmlDecode(tile.NavigationUri.ToString()).IndexOf("&topicname=", firstTilePostId); tilePostId = HttpUtility.HtmlDecode(tile.NavigationUri.ToString().Substring(firstTilePostId, lastTilePostId - firstTilePostId)); string tileCatId; int firstTileCatId = HttpUtility.HtmlDecode(tile.NavigationUri.ToString()).IndexOf("?idcat=") + "?idcat=".Length; int lastTileCatId = HttpUtility.HtmlDecode(tile.NavigationUri.ToString()).IndexOf("&idtopic=", firstTileCatId); tileCatId = HttpUtility.HtmlDecode(tile.NavigationUri.ToString().Substring(firstTileCatId, lastTileCatId - firstTileCatId)); foreach (TopicFav fav in favObject) { if (tilePostId == fav.TopicIdFav) { containsFav = true; } } if (containsFav) { StandardTileData NewTileData = new StandardTileData { BackContent = "Nouveaux messages !", BackgroundImage = new Uri("Images/tiles/" + HFR7.HFRClasses.GetCatName.ShortNameFromId(tileCatId) + "_new.png", UriKind.Relative), BackBackgroundImage = new Uri("Images/tiles/unread.png", UriKind.Relative) }; tile.Update(NewTileData); } else { StandardTileData NewTileData = new StandardTileData { BackContent = "Pas de nouveaux messages", BackgroundImage = new Uri("Images/tiles/" + HFR7.HFRClasses.GetCatName.ShortNameFromId(tileCatId) + ".png", UriKind.Relative), BackBackgroundImage = new Uri("Images/tiles/read.png", UriKind.Relative) }; tile.Update(NewTileData); } } } //////////////////////////////// // Mise à jour de la tile principale //////////////////////////////// int numberOfUnreadFav = favObject.Count; ShellTile MainTileToFind = ShellTile.ActiveTiles.FirstOrDefault(); StandardTileData MainNewAppTileData = new StandardTileData { Count = numberOfUnreadFav }; MainTileToFind.Update(MainNewAppTileData); //////////////////////////////// // Mise à jour des MP //////////////////////////////// ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(); if (mpArray.Length != 0 && isMpNotified == "false" && activateMpNotif == "true" && DateTime.Now.Hour > 9 && DateTime.Now.Hour < 23) { if (Convert.ToInt32(mpArray[0].Split(' ')[2]) > 0) { ShellToast mpToast = new ShellToast(); mpToast.Title = "HFR7"; mpToast.Content = "1 nouveau message privé."; mpToast.Show(); StandardTileData NewAppTileData = new StandardTileData { BackTitle = "HFR7", BackBackgroundImage = new Uri("Images/tiles/backtile.png", UriKind.Relative), BackContent = "Nouveau message privé !" }; if (isoStore.FileExists("isMpNotified.txt")) { isoStore.DeleteFile("isMpNotified.txt"); } using (var file = isoStore.OpenFile("isMpNotified.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) { using (var writer = new StreamWriter(file)) { writer.Write("true"); } } TileToFind.Update(NewAppTileData); } } else if (mpArray.Length == 0) { if (isoStore.FileExists("isMpNotified.txt")) { isoStore.DeleteFile("isMpNotified.txt"); } using (var file = isoStore.OpenFile("isMpNotified.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) { using (var writer = new StreamWriter(file)) { writer.Write("false"); } } } ////////////////////////////////// //// Notifications ////////////////////////////////// //ShellToast notifToast = new ShellToast(); //XmlSerializer serializer = new XmlSerializer(notifTopicList.GetType()); //using (var file = isoStore.OpenFile("notifications.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read)) //{ // using (var reader = new StreamReader(file)) // { // try // { // object deserialized = serializer.Deserialize(reader.BaseStream); // notifTopicList = (List<NotifTopics>)deserialized; // } // catch { } // } //} //foreach (TopicFav fav in favObject) //{ // int containsNotif = -1; // int h = 0; // foreach (NotifTopics notifTopic in notifTopicList) // { // if (fav.TopicIdFav == notifTopic.TopicId && notifTopic.TopicIsNotif == false && DateTime.Now.Hour > 9 && DateTime.Now.Hour < 23) // { // containsNotif = h; // notifToast.Title = "HFR7"; // notifToast.Content = "Nouvelle réponse : " + fav.TopicNameFav; // notifToast.NavigationUri = new Uri("/ReadTopic.xaml?idcat=" + fav.TopicCatIdFav + "&idtopic=" + fav.TopicIdFav + "&topicname=" + HttpUtility.UrlEncode(fav.TopicNameFav) + "&pagenumber=" + fav.TopicPage + "&jump=" + fav.TopicJump + "&numberofpages=" + fav.TopicNumberOfPages, UriKind.Relative); // notifToast.Show(); // } // h++; // } // if (containsNotif != -1) // { // notifTopicList.RemoveAt(containsNotif); // notifTopicList.Add(new NotifTopics() // { // TopicCatId = fav.TopicCatIdFav.ToString(), // TopicId = fav.TopicIdFav.ToString(), // TopicIsNotif = true, // TopicJump = fav.TopicJump.ToString(), // TopicName = fav.TopicNameFav.ToString(), // TopicNumberOfPages = fav.TopicNumberOfPages.ToString(), // TopicPageNumber = fav.TopicPage.ToString() // }); // } // if (isoStore.FileExists("notifications.xml")) isoStore.DeleteFile("notifications.xml"); // using (var file = isoStore.OpenFile("notifications.xml", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) // { // using (var writer = new StreamWriter(file)) // { // try // { // serializer.Serialize(writer.BaseStream, notifTopicList); // } // catch { } // } // } //} NotifyComplete(); } catch { TileErreur(); } } }); } catch { NotifyComplete(); } }
/// <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, FileAccess.Read, FileShare.Read, isoFile)) { this.player.SetSource(stream); } } else { InvokeCallback(MediaError, MediaErrorFileNotPresent, 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); } } }
protected void LoadData() { using (Save_Game = IsolatedStorageFile.GetUserStoreForApplication()) { if (Save_Game.FileExists("BlowToTheBall_Save")) { using (File_Stream = Save_Game.OpenFile("BlowToTheBall_Save", System.IO.FileMode.Open)) { if (File_Stream != null) { tmpbytes = new byte[2]; //Проверка ID сохранения if (File_Stream.Read(tmpbytes, 0, 2) > 0) { if (System.BitConverter.ToInt16(tmpbytes, 0) != firm_id) { return; } } //Чтение активности звука if (File_Stream.Read(tmpbytes, 0, 1) > 0) { Sound = System.BitConverter.ToBoolean(tmpbytes, 0); } else { Sound = false; } //Чтение резервных переменных File_Stream.Read(tmpbytes, 0, 1); File_Stream.Read(tmpbytes, 0, 2); File_Stream.Read(tmpbytes, 0, 2); File_Stream.Read(tmpbytes, 0, 2); File_Stream.Read(tmpbytes, 0, 2); File_Stream.Read(tmpbytes, 0, 2); File_Stream.Read(tmpbytes, 0, 2); File_Stream.Read(tmpbytes, 0, 2); File_Stream.Read(tmpbytes, 0, 2); File_Stream.Read(tmpbytes, 0, 2); for (i = 0; i < Level_Count; i++) { if (File_Stream.Read(tmpbytes, 0, 1) > 0) { Level_Data[i].Used = System.BitConverter.ToBoolean(tmpbytes, 0); } else { Level_Data[i].Used = false; } if (File_Stream.Read(tmpbytes, 0, 2) > 0) { Level_Data[i].Score = System.BitConverter.ToInt16(tmpbytes, 0); } else { Level_Data[i].Score = 0; } if (File_Stream.Read(tmpbytes, 0, 2) > 0) { Level_Data[i].Stars = System.BitConverter.ToInt16(tmpbytes, 0); } else { Level_Data[i].Stars = 0; } } } } } } }
public Task <bool> GetFileExistsAsync(string path) { return(Task.FromResult(_isolatedStorageFile.FileExists(path))); }
//Load recently scrobbled songs async Task LoadRecent() { //Check account name and password if (String.IsNullOrWhiteSpace(vApplicationSettings["LastfmAccount"].ToString()) || String.IsNullOrWhiteSpace(vApplicationSettings["LastfmPassword"].ToString()) || String.IsNullOrWhiteSpace(vApplicationSettings["LastfmSessionKey"].ToString())) { Dispatcher.BeginInvoke(delegate { txt_RecentStats.Text = "Please set your Last.fm account name and password in the settings tab and login to view your recently scrobbled songs."; lb_RecentListBox.Items.Clear(); }); return; } //Connect to last.fm and get recently scrobbled songs try { ProgressDisableUI("Refreshing recent scrobbles..."); Dispatcher.BeginInvoke(delegate { lb_RecentListBox.Items.Clear(); }); XDocument RecentXDoc = null; if (NetworkInterface.GetIsNetworkAvailable()) { Dispatcher.BeginInvoke(delegate { txt_RecentOffline.Visibility = Visibility.Collapsed; }); using (HttpClient HttpClientRecent = new HttpClient()) { HttpClientRecent.DefaultRequestHeaders.Add("User-Agent", "ScrobbleMe"); HttpClientRecent.DefaultRequestHeaders.Add("Accept-Charset", "UTF-8"); HttpClientRecent.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store"); //Yes, I know I didn't remove the api key. RecentXDoc = XDocument.Parse(await HttpClientRecent.GetStringAsync(new Uri("https://ws.audioscrobbler.com/2.0/?api_key=a62159e276986acf81f6990148b06ae3&method=user.getRecentTracks&user="******"LastfmAccount"].ToString()) + "&limit=30&nc=" + Environment.TickCount))); } //Save Data to XML using (IsolatedStorageFileStream IsolatedStorageFileStream = IsolatedStorageFile.GetUserStoreForApplication().CreateFile("RecentData.xml")) { using (StreamWriter StreamWriter = new StreamWriter(IsolatedStorageFileStream)) { StreamWriter.WriteLine(RecentXDoc); } } } else { using (IsolatedStorageFile IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (IsolatedStorageFile.FileExists("RecentData.xml")) { Dispatcher.BeginInvoke(delegate { txt_RecentOffline.Visibility = Visibility.Visible; }); using (IsolatedStorageFileStream IsolatedStorageFileStream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("RecentData.xml", FileMode.Open)) { RecentXDoc = XDocument.Load(IsolatedStorageFileStream); } } } } //Check if there is any content in xml if (RecentXDoc == null) { txt_RecentStats.Text = "It seems like there is no recent scrobbles data available, please refresh the recent scrobbles when you have an internet connection available."; } else { foreach (XElement Info in RecentXDoc.Descendants("track")) { string Artist = Info.Element("artist").Value; string Title = Info.Element("name").Value; string Image = "/Assets/NoCover.jpg"; string Date = "Not available"; if (Info.Element("date") != null) { DateTime DTDate = DateTime.Parse(Info.Element("date").Value).ToLocalTime(); Date = DTDate.ToString("d MMMM yyyy", new System.Globalization.CultureInfo("en-US")) + ", " + DTDate.ToShortTimeString(); } else { Date = "Listening now"; } if ((bool)vApplicationSettings["LastfmDownloadCovers"]) { if (!String.IsNullOrEmpty(Info.Element("image").Value) && Info.Element("image").Value.StartsWith("http")) { Image = Info.Element("image").Value.Replace("/34s/", "/64s/"); } } Dispatcher.BeginInvoke(delegate { lb_RecentListBox.Items.Add(new RecentlySongsList() { Artist = Artist, Title = Title, Date = Date, Image = Image }); }); } Dispatcher.BeginInvoke(delegate { if (lb_RecentListBox.Items.Count == 0) { lb_RecentListBox.Visibility = Visibility.Collapsed; txt_RecentStats.Text = "It seems like you haven't played any songs yet, now it's time to start playing some songs to scrobble!"; } else { foreach (XElement Info in RecentXDoc.Descendants("recenttracks")) { txt_RecentStats.Text = "Total scrobbles on your Last.fm profile: " + Info.Attribute("total").Value + "\nYou have recently scrobbled the following songs:"; } //if (lb_RecentListBox.Items.Count > 0) { lb_RecentListBox.ScrollIntoView(lb_RecentListBox.Items[0]); } lb_RecentListBox.Visibility = Visibility.Visible; } }); } } catch { Dispatcher.BeginInvoke(delegate { lb_RecentListBox.Visibility = Visibility.Collapsed; txt_RecentStats.Text = "Failed to connect to Last.fm, please check your Last.fm account settings, try to relog into your account or check your internet connection.\n\nIt could also be that the requested data is not available at Last.fm, please try again later on to see if the requested data is available for you."; }); } ProgressEnableUI(); return; }
/// <summary> /// This function loads a stl mesh into a vertex list /// from a specified file with certain parameters. /// </summary> /// <param name="filePath">The path of the stl to be imported</param> /// <param name="meshColor">The color that the mesh should have</param> /// <param name="centrePosition">The position that the model should be centred on.</param> /// <returns></returns> static public List <VertexPositionColoredNormal> loadStlFromFile(string filePath, Color meshColor) { List <VertexPositionColoredNormal> vertexList = new List <VertexPositionColoredNormal>();//the list of vertices that will be returned IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication(); if (!isoFile.FileExists(filePath))//File.Exists(filePath)) { return(new List <VertexPositionColoredNormal>()); } IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, isoFile); //FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate);//the file stream used to read the stl file BinaryReader binaryReader = new BinaryReader(fileStream); //the binary reader used to check the stl is binary and read it if it is binaryReader.ReadBytes(80); //read the binary hearder int faceCount = binaryReader.ReadInt32(); //read the amount of faces if (fileStream.Length != 84 + faceCount * 50) //check if the file is binary by comparing the expected length for one to the actual length { //we are now reading an ascii stl binaryReader.Dispose(); //dispose of the binary reader because it is not needed anymore fileStream.Dispose(); //dispode of the filestream because it is not needed anymore //Convert the model from ascii to binary StlFormatConverter.convertAsciiToBinary(filePath); //Stop here if we should stop loading if (!Values.stl_IsBusy) { return(null); } fileStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, isoFile); //new FileStream(filePath, FileMode.Open);//the file stream used to read the stl file binaryReader = new BinaryReader(fileStream); //the binary reader used to check the stl is binary and read it if it is binaryReader.ReadBytes(80); //read the binary hearder faceCount = binaryReader.ReadInt32(); //read the amount of faces loadBinary(ref vertexList, binaryReader, faceCount, meshColor); //load the binary stl into the vertex list fileStream.Dispose(); } else { //we are now reading a binary stl loadBinary(ref vertexList, binaryReader, faceCount, meshColor); //load the binary stl into the vertex list fileStream.Dispose(); //we dispose the filestream after it has been used } //Stop here if we should stop loading if (!Values.stl_IsBusy) { return(null); } if (vertexList.Count < 1) //check if the list is empty { throw new Exception("Something went wrong trying to import the stl"); //throw an exception if it is } return(vertexList); //return the generated vertex list }
/// <summary> /// 验证文件 /// </summary> /// <param name="p_FilePath">文件路径</param> /// <returns></returns> private static bool ValidFilePath(String p_FilePath) { return(StorageFileManage.FileExists(p_FilePath)); }