/// <summary>
        /// Informs the screen manager to serialize its state to disk.
        /// </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("ScreenManager"))
                {
                    DeleteState(storage);
                }

                // otherwise just create the directory
                else
                {
                    storage.CreateDirectory("ScreenManager");
                }

                // create a file we'll use to store the list of screens in the stack
                using (IsolatedStorageFileStream stream = storage.CreateFile("ScreenManager\\ScreenList.dat"))
                {
                    using (BinaryWriter writer = new BinaryWriter(stream))
                    {
                        // write out the full name of all the types in our stack so we can
                        // recreate them if needed.
                        foreach (GameScreen screen in screens)
                        {
                            if (screen.IsSerializable)
                            {
                                writer.Write(screen.GetType().AssemblyQualifiedName);
                            }
                        }
                    }
                }

                // 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;
                foreach (GameScreen screen in screens)
                {
                    if (screen.IsSerializable)
                    {
                        string fileName = string.Format("ScreenManager\\Screen{0}.dat", screenIndex);

                        // open up the stream and let the screen serialize whatever state it wants
                        using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
                        {
                            screen.Serialize(stream);
                        }

                        screenIndex++;
                    }
                }
            }
        }
Exemple #2
0
        private static void SetAudioAgentPlaylistImpl(List <AudioObj> tracks, StatisticsActionSource actionSource)
        {
            if (tracks == null)
            {
                return;
            }
            tracks = tracks.Where <AudioObj>((Func <AudioObj, bool>)(track => track.content_restricted == 0)).ToList <AudioObj>();
            if (tracks.Count == 0)
            {
                return;
            }



            //IEnumerable<AudioObj> arg_59_0 = tracks;
            //Func<AudioObj, string> arg_59_1 = new Func<AudioObj, string>(a => a.UniqueId);
            //tracks = Enumerable.ToList<AudioObj>(arg_59_0.Distinct(arg_59_1));


//      tracks = tracks.Distinct<AudioObj>((Func<AudioObj, string>) (a => a.UniqueId)).ToList<AudioObj>();//todo: bug
            Playlist playlist1 = new Playlist();

            playlist1.Metadata = new Metadata()
            {
                LastUpdated  = DateTime.Now,
                ActionSource = actionSource
            };
            List <AudioObj> audioObjList = tracks;

            playlist1.Tracks = audioObjList;
            Playlist playlist2 = playlist1;

            lock (PlaylistManager._lockObj)
            {
                try
                {
                    using (IsolatedStorageFile storeForApplication = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        PlaylistManager.metadataAccessMutex.WaitOne();
                        using (BinaryWriter writer = new BinaryWriter((Stream)storeForApplication.CreateFile(PlaylistManager.PlaylistMetadataFileName)))
                            writer.Write <Metadata>(playlist2.Metadata, false);
                        PlaylistManager.metadataAccessMutex.ReleaseMutex();
                        PlaylistManager.playlistAccessMutex.WaitOne();
                        using (BinaryWriter writer = new BinaryWriter((Stream)storeForApplication.CreateFile(PlaylistManager.PlaylistFileName)))
                            writer.Write <Playlist>(playlist2, false);
                        PlaylistManager.playlistAccessMutex.ReleaseMutex();
                        PlaylistManager._playlistCached = playlist2;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error("Failed to set playlist", ex);
                }
            }
        }
        public static void StorePhotoModel(PhotoModel model)
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!storage.DirectoryExists(_photoModelPath))
                {
                    storage.CreateDirectory(_photoModelPath);
                }

                // buffer.data

                if (storage.FileExists(_photoModelPath + @"\" + _photoModelBufferFilename))
                {
                    storage.DeleteFile(_photoModelPath + @"\" + _photoModelBufferFilename);
                }

                IBuffer buffer = model.Buffer;

                if (buffer != null)
                {
                    IsolatedStorageFileStream originalFile = storage.CreateFile(_photoModelPath + @"\" + _photoModelBufferFilename);

                    Stream bufferStream = buffer.AsStream();

                    bufferStream.CopyTo(originalFile);
                    bufferStream.Flush();
                    bufferStream.Close();
                    bufferStream.Dispose();

                    originalFile.Flush();
                    originalFile.Close();
                    originalFile.Dispose();
                }

                // properties.xml

                if (storage.FileExists(_photoModelPath + @"\" + _photoModelPropertiesFilename))
                {
                    storage.DeleteFile(_photoModelPath + @"\" + _photoModelPropertiesFilename);
                }

                IsolatedStorageFileStream propertiesFile = storage.CreateFile(_photoModelPath + @"\" + _photoModelPropertiesFilename);
                XmlSerializer             serializer     = new XmlSerializer(typeof(PhotoModel));
                TextWriter textWriter = new StreamWriter(propertiesFile);

                serializer.Serialize(textWriter, model);

                textWriter.Flush();
                propertiesFile.Flush();

                textWriter.Close();
                propertiesFile.Close();
            }
        }
Exemple #4
0
        public static bool FirstStart()
        {
            bool result;

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                result = myIsolatedStorage.FileExists("TotalScore.txt");
                if (!result)
                {
                    myIsolatedStorage.CreateFile("TotalScore.txt"); myIsolatedStorage.CreateFile("HighScore.txt");
                }
            }
            return(result);
        }
        //saves a 99x99 and 200x200 image to the phone
        private void SaveImageToPhone(GameData data)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!isoStore.DirectoryExists("/GameImages/"))
                {
                    isoStore.CreateDirectory("/GameImages/");
                }

                IsolatedStorageFileStream isoStream = isoStore.CreateFile("/GameImages/" + data.GameID + "-" + data.GameTitle + "-cover-image-99.jpg");

                BitmapImage image = data.GameCoverCacheImage;
                image.DecodePixelHeight = 99;
                image.DecodePixelWidth  = 99;

                var saveImage = new WriteableBitmap(image);

                saveImage.SaveJpeg(isoStream, 99, 99, 0, 100);

                isoStream.Close();

                try
                {
                    isoStream = isoStore.CreateFile("/GameImages/" + data.GameID + "-" + data.GameTitle + "-cover-image-200.jpg");
                }
                catch (Exception)
                {
                    //for some reason this crashes when trying to add certain games....
                    //gotta figure that out...
                    //Metro: Last Light - PS3

                    return;
                }

                image = data.GameCoverCacheImage;
                image.DecodePixelHeight = 200;
                image.DecodePixelWidth  = 200;

                saveImage = new WriteableBitmap(image);
                saveImage.SaveJpeg(isoStream, 200, 200, 0, 100);

                saveImage = null;
                image     = null;
                data.GameCoverCacheImage = null;

                isoStream.Close();
                isoStream.Dispose();
            }
        }
Exemple #6
0
        public bool DeCompress(string sourceFilePath, string destinationPath)
        {
            try
            {
                Stream stream = storage.OpenFile(sourceFilePath, System.IO.FileMode.Open);
                using (ZipInputStream zs = new ZipInputStream(stream))
                {
                    ZipEntry entry = null;
                    //解压缩*.rar文件运行至此处出错:Wrong Local header signature: 0x21726152,解压*.zip文件不出错
                    while ((entry = zs.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(entry.Name);
                        string fileName      = Path.GetFileName(entry.Name);

                        if (!string.IsNullOrEmpty(fileName))
                        {
                            storage.CreateDirectory(Path.Combine(destinationPath, directoryName));
                            using (IsolatedStorageFileStream streamWriter = storage.CreateFile(Path.Combine(destinationPath, directoryName, fileName)))
                            {
                                int    size = 2048;
                                byte[] data = new byte[size];
                                while (true)
                                {
                                    size = zs.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                stream.Close();
            }
            catch (System.Exception Ex)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(Ex.Message);
                });
            }
            return(true);
        }
Exemple #7
0
        private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            //O resultado do download chega através do argumento "e" recepcionado por esse método
            if (!e.Cancelled && e.Error == null)
            {
                byte[] arquivoBytes = new byte[e.Result.Length];
                e.Result.Read(arquivoBytes, 0, arquivoBytes.Length);

                using (IsolatedStorageFile isoStore =
                           IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream isoStream =
                               isoStore.CreateFile("teste.txt"))
                    {
                        isoStream.Write(arquivoBytes, 0, arquivoBytes.Length);
                        isoStream.Close();
                    }

                    resolveVisibilidade();
                }
                MessageBox.Show("Busca Concluída");
            }
            else
            {
                MessageBox.Show("Erro na conexão, por favor verifique se o coletor está ligado e se o seu celular está conectado ao coletor pela rede sem fio");
            }
        }
Exemple #8
0
        public void SaveToDisk()
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(FileName))
                {
                    store.DeleteFile(FileName);
                }

                using (IsolatedStorageFileStream stream = store.CreateFile(FileName))
                {
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        List <SquareViewModel> s = new List <SquareViewModel>();
                        foreach (SquareViewModel item in GameArray)
                        {
                            s.Add(item);
                        }

                        XmlSerializer serializer = new XmlSerializer(s.GetType());
                        serializer.Serialize(writer, s);
                    }
                }
            }
        }
Exemple #9
0
    public static void Main()
    {
        using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null))
        {
            isoStore.CreateDirectory("TopLevelDirectory");
            isoStore.CreateDirectory("TopLevelDirectory/SecondLevel");
            isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");
            Console.WriteLine("Created directories.");

            isoStore.CreateFile("InTheRoot.txt");
            Console.WriteLine("Created a new file in the root.");

            isoStore.CreateFile("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt");
            Console.WriteLine("Created a new file in the InsideDirectory.");
        }
    }
        private void SerializeStoreData(IsolatedStorageFile isoStore)
        {
            if (isoStore.FileExists(STORE_FILENAME))
            {
                isoStore.DeleteFile(STORE_FILENAME);
            }

            using (IsolatedStorageFileStream isoStream = isoStore.CreateFile(STORE_FILENAME))
            {
                StoreData data = new StoreData();
                if (null != CurrentBlog)
                {
                    data.Xmlrpc = CurrentBlog.Xmlrpc;
                }
                else
                {
                    data.Xmlrpc = "";
                }
                data.Comment      = CurrentComment;
                data.PostListItem = CurrentPostListItem;
                data.PageListItem = CurrentPageListItem;
                data.Post         = CurrentPost;

                XmlSerializer serializer = new XmlSerializer(typeof(StoreData));
                serializer.Serialize(isoStream, data);
            }
        }
Exemple #11
0
 /// <summary>
 /// 创建文件
 /// </summary>
 /// <param name="DircetoryName">文件夹</param>
 /// <param name="path">文件路径</param>
 /// <param name="bytes">文件流</param>
 public static void CreateFile(string DircetoryName, string path, byte[] bytes)
 {
     try
     {
         using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
         {
             if (!file.DirectoryExists(DircetoryName))
             {
                 file.CreateDirectory(DircetoryName);
             }
             path = string.Format(@"{0}\{1}", DircetoryName, path);
             if (file.FileExists(path))
             {
                 file.DeleteFile(path);
             }
             using (IsolatedStorageFileStream stream = file.CreateFile(path))
             {
                 if (stream.CanWrite)
                 {
                     //可加密后再进行缓存
                     //byte[] secBytes= Security.Encryption.Encrypt(bytes, DircetoryName);
                     stream.Write(bytes, 0, bytes.Length);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw new Exception("创建独立存储文件发生异常!", ex);
     }
 }
Exemple #12
0
        private void CopyToIsolatedStorage()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string[] files = new string[] { "Enemy_at_the_gates.mp3", "Requiem.mp3", "Sunday_Walk.mp3" };

                foreach (var _fileName in files)
                {
                    if (!storage.FileExists(_fileName))
                    {
                        string             _filePath = "Audio/" + _fileName;
                        StreamResourceInfo resource  = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));

                        using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))
                        {
                            int    chunkSize = 4096;
                            byte[] bytes     = new byte[chunkSize];
                            int    byteCount;

                            while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
                            {
                                file.Write(bytes, 0, byteCount);
                            }
                        }
                    }
                }
            }
        }
        public static void WriteToIsolatedStorage(IsolatedStorageFile storage, System.IO.Stream inputStream, string fileName)
        {
            IsolatedStorageFileStream outputStream = null;

            try
            {
                if (!storage.DirectoryExists(imageStorageFolder))
                {
                    storage.CreateDirectory(imageStorageFolder);
                }
                if (storage.FileExists(fileName))
                {
                    storage.DeleteFile(fileName);
                }
                outputStream = storage.CreateFile(fileName);
                byte[] buffer = new byte[inputStream.Length];
                int    read;
                while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    outputStream.Write(buffer, 0, read);
                }
                outputStream.Close();
            }
            catch
            {
                //We cannot do anything here.
                if (outputStream != null)
                {
                    outputStream.Close();
                }
            }
        }
Exemple #14
0
        public static async Task SetImage(Uri uri)
        {
            string fileName  = uri.Segments[uri.Segments.Length - 1];
            string imageName = BackgroundRoot + fileName;
            string iconName  = IconRoot + fileName;

            using (IsolatedStorageFile storageFolder = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!storageFolder.DirectoryExists(BackgroundRoot))
                {
                    storageFolder.CreateDirectory(BackgroundRoot);
                }

                if (!storageFolder.FileExists(imageName))
                {
                    using (IsolatedStorageFileStream stream = storageFolder.CreateFile(imageName))
                    {
                        HttpClient client      = new HttpClient();
                        byte[]     flikrResult = await client.GetByteArrayAsync(uri);

                        await stream.WriteAsync(flikrResult, 0, flikrResult.Length);
                    }
                }
                storageFolder.CopyFile(imageName, iconName);
            }
            //Set the lockscreen
            await SetLockScreen(fileName);
        }
        public string SaveReceipt(ProductListing productListing, bool returnReceipt)
        {
            if (productListing.ProductType == ProductType.Unknown)
            {
                return(string.Empty); // nothing to do with this one.
            }
            string mockReceipt = string.Format(ReceiptTemplate,
                                               productListing.FormattedPrice,
                                               DateTime.Now.ToLongTimeString(),
                                               Guid.NewGuid().ToString(),
                                               productListing.ProductId,
                                               productListing.ProductType.ToString());


            IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication();
            string targetFileName         = Path.Combine(ReceiptStore, productListing.ProductId + ".xml");

            if (!userStore.FileExists(targetFileName))
            {
                IsolatedStorageFileStream stream = userStore.CreateFile(targetFileName);
                var sw = new StreamWriter(stream);
                sw.WriteLine(mockReceipt);
                sw.Close();
            }

            return(mockReceipt);
        }
Exemple #16
0
    private void SaveToIsoStore(string fileName, byte[] data)
    {
        string strBaseDir = string.Empty;
        string delimStr   = "/";

        char[]   delimiter = delimStr.ToCharArray();
        string[] dirsPath  = fileName.Split(delimiter);
        //Get the IsoStore.
        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

        //Re-create the directory structure.
        for (int i = 0; i < dirsPath.Length - 1; i++)
        {
            strBaseDir = System.IO.Path.Combine(strBaseDir, dirsPath[i]);
            isoStore.CreateDirectory(strBaseDir);
        }
        //Remove the existing file.
        if (isoStore.FileExists(fileName))
        {
            isoStore.DeleteFile(fileName);
        }
        //Write the file.
        using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fileName)))
        {
            bw.Write(data);
            bw.Close();
        }
    }
Exemple #17
0
        public void Save()
        {
            try
            {
                XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root"));

                XElement settingsNode = new XElement("Settings");
                doc.Root.Add(settingsNode);

                settingsNode.Add(
                    new XElement("IsFullScreen", IsFullScreen.ToString()),
                    new XElement("AlwaysShowHPBars", AlwaysShowHPBars.ToString()),
                    new XElement("ShowBountyValues", AlwaysShowHPBars.ToString())
                    );


                // Save
#if WINDOWS
                doc.Save(Path, SaveOptions.None);
#endif
#if XBOX
                if (FileStorage.FileExists(Path))
                {
                    FileStorage.DeleteFile(Path);
                }
                IsolatedStorageFileStream stream = FileStorage.CreateFile(Path);
                doc.Save(stream);
                stream.Close();
#endif
            }
            catch { }
        }
            public static void WriteTextToFile(string fileName, string fileContent)
            {
#if OPENSILVER || SILVERLIGHT
                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
#else
                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly())
#endif
                {
                    IsolatedStorageFileStream fs = null;
                    using (fs = storage.CreateFile(fileName))
                    {
                        if (fs != null)
                        {
                            //using (StreamWriter sw = new StreamWriter(fs))
                            //{
                            //    sw.Write(fileContent);
                            //}
                            Encoding encoding = new UTF8Encoding();
                            byte[]   bytes    = encoding.GetBytes(fileContent);
                            fs.Write(bytes, 0, bytes.Length);
                            fs.Close();
                        }
                    }
                }
            }
        public void UsedSize()
        {
            IsolatedStorageFile       isf  = IsolatedStorageFile.GetUserStoreForAssembly();
            IsolatedStorageFileStream isfs = isf.CreateFile("file");
            StreamWriter writer            = new StreamWriter(isfs);

            writer.WriteLine("hello mono");
            writer.Close();

            Assert.AreEqual(true, isf.UsedSize > 0, "#A0");

            isf.Close();
            try {
                Console.WriteLine(isf.UsedSize);
                Assert.Fail("#Exc1");
            } catch (InvalidOperationException) {
            }

            isf.Dispose();
            try {
                Console.WriteLine(isf.UsedSize);
                Assert.Fail("#Exc2");
            } catch (ObjectDisposedException) {
            }
        }
Exemple #20
0
        private void HandlePhotoResult(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                String tempJPEG           = "" + _baby.Id + ".jpeg";
                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();

                if (store.FileExists(tempJPEG))
                {
                    store.DeleteFile(tempJPEG);
                }

                IsolatedStorageFileStream fileStream = store.CreateFile(tempJPEG);
                BitmapImage bitmap = new BitmapImage();

                bitmap.SetSource(e.ChosenPhoto);
                WriteableBitmap wb = new WriteableBitmap(bitmap);

                Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
                fileStream.Close();

                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    Photo = "isostore:/" + tempJPEG;
                });
            }
        }
Exemple #21
0
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="DircetoryName">文件夹</param>
        /// <param name="path">文件路径</param>
        /// <param name="bytes">文件流</param>
        public static void CreateFile(string DircetoryName, string path, XElement xmlDoc)
        {
            try
            {
                using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!file.DirectoryExists(DircetoryName))
                    {
                        file.CreateDirectory(DircetoryName);
                    }
                    path = string.Format(@"{0}\{1}", DircetoryName, path);
                    if (file.FileExists(path))
                    {
                        file.DeleteFile(path);
                    }

                    using (IsolatedStorageFileStream stream = file.CreateFile(path))
                    {
                        xmlDoc.Save(stream);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("创建独立存储文件发生异常!", ex);
            }
        }
Exemple #22
0
        /// <summary>
        /// Writes audio data from memory to isolated storage
        /// </summary>
        /// <returns></returns>
        private void SaveAudioClipToLocalStorage()
        {
            if (this.memoryStream == null || this.memoryStream.Length <= 0)
            {
                return;
            }

            this.UpdateWavHeader(this.memoryStream);

            try
            {
                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string directory = Path.GetDirectoryName(audioFile);

                    if (!isoFile.DirectoryExists(directory))
                    {
                        isoFile.CreateDirectory(directory);
                    }

                    this.memoryStream.Seek(0, SeekOrigin.Begin);

                    using (IsolatedStorageFileStream fileStream = isoFile.CreateFile(audioFile))
                    {
                        this.memoryStream.CopyTo(fileStream);
                    }
                }
            }
            catch (Exception)
            {
                //TODO: log or do something else
                throw;
            }
        }
        private void ButtonSaveToIsolatedStorageFile_Click(object sender, RoutedEventArgs e)
        {
            if (!DisplayWarningIfRunningFromLocalFileSystemOnInternetExplorer())
            {
                string fileName = "SampleFile.txt";
                string data     = TextBoxFileStorageDemo.Text;

                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly())
                {
                    IsolatedStorageFileStream fs = null;
                    using (fs = storage.CreateFile(fileName))
                    {
                        if (fs != null)
                        {
                            Encoding encoding = new UTF8Encoding();
                            byte[]   bytes    = encoding.GetBytes(data);
                            fs.Write(bytes, 0, bytes.Length);
                            fs.Close();
                            MessageBox.Show("A new file named SampleFile.txt was successfully saved to the storage.");
                        }
                        else
                        {
                            MessageBox.Show("Unable to save the file SampleFile.txt to the storage.");
                        }
                    }
                }
            }
        }
        public static void SaveFilesToIsoStore(string[] fns)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                foreach (string fn in fns)
                {
                    StreamResourceInfo sri = Application.GetResourceStream(new Uri(fn, UriKind.Relative));
                    using (BinaryReader br = new BinaryReader(sri.Stream))
                    {
                        byte[]   data         = br.ReadBytes((int)sri.Stream.Length);
                        string[] pathElements = fn.Split(System.IO.Path.DirectorySeparatorChar);

                        // Create dir structure
                        string dir = String.Empty;
                        for (int i = 0; i < pathElements.Length - 1; i++)
                        {
                            dir = System.IO.Path.Combine(dir, pathElements[i]);
                            if (!isoStore.DirectoryExists(dir))
                            {
                                isoStore.CreateDirectory(dir);
                            }
                        }

                        using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fn)))
                        {
                            bw.Write(data);
                            bw.Close();
                        }
                    }
                }
            }
        }
        private void CopyToIsolatedStorage()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string file_name = "Data.xml";

                if (!storage.FileExists(file_name))
                {
                    string             _filePath = "DataHistory/" + file_name;
                    StreamResourceInfo resource  = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));

                    using (IsolatedStorageFileStream file = storage.CreateFile(file_name))
                    {
                        int    chunkSize = 4096;
                        byte[] bytes     = new byte[chunkSize];
                        int    byteCount;

                        while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
                        {
                            file.Write(bytes, 0, byteCount);
                        }
                    }
                }
            }
        }
Exemple #26
0
        /*
         * "Button_Pressed.mp3",
         *                                      "categories.mp3",
         *                                      "cheer.mp3",
         *      "gameplay.mp3","menu.mp3","score_screen.mp3","unlock.mp3","wrong_answer8.mp3",
         */
        private void CopyToIsolatedStorage()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string[] files = new string[] {
                    "ButtonPressed.wav",
                    "unlock.wav",
                    "wronganswer.wav"
                };

                foreach (var _fileName in files)
                {
                    if (!storage.FileExists(_fileName))
                    {
                        string             _filePath = "sounds/" + _fileName;
                        StreamResourceInfo resource  = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));

                        using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))
                        {
                            int    chunkSize = 4096;
                            byte[] bytes     = new byte[chunkSize];
                            int    byteCount;

                            while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
                            {
                                file.Write(bytes, 0, byteCount);
                            }
                        }
                    }
                }
            }
        }
Exemple #27
0
        public static void SaveStreamToFile(Stream stream, string cachePath)
        {
            IsolatedStorageFileStream fileStream = null;

            try
            {
                byte[] buffer = new byte[stream.Length];

                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
                if (!store.FileExists(cachePath))
                {
                    fileStream = store.CreateFile(cachePath);

                    stream.Read(buffer, 0, buffer.Length);
                    fileStream.Write(buffer, 0, buffer.Length);
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
        public override Stream CreateFile(string path)
        {
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            Stream stream             = store.CreateFile(path);

            return(stream);
        }
Exemple #29
0
        // appPath의 리소스를 storagePath에 넣습니다.
        static public bool CopyResourceToStorage(string appPath, string storagePath, bool bForce = false)
        {
            StreamResourceInfo info = Application.GetResourceStream(new Uri(appPath, UriKind.Relative));

            if (info == null)
            {
                return(false);
            }

            if (!bForce && isoStorage.FileExists(storagePath))
            {
                return(true);
            }

            // storagePath에 디렉토리 자동생성
            if (!MakeDir(Path.GetDirectoryName(storagePath)))
            {
                return(false);
            }

            byte[] buffer = new byte[1024 * 32]; // 버퍼는 32kb

            using (var reader = new BinaryReader(info.Stream))
                using (var writer = new BinaryWriter(isoStorage.CreateFile(storagePath)))
                {
                    int readBytes = 0;
                    while ((readBytes = reader.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        writer.Write(buffer, 0, readBytes);
                    }
                }

            return(true);
        }
Exemple #30
0
        public static void SaveImage(string nameFile, BitmapImage bitmap)
        {
            // Create a filename for JPEG file in isolated storage.
            // String tempJPEG = "logo.jpg";

            // Create virtual store and file stream. Check for duplicate tempJPEG files.
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (myIsolatedStorage.FileExists(nameFile))
                {
                    myIsolatedStorage.DeleteFile(nameFile);
                }

                IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(nameFile);

                //StreamResourceInfo sri = null;
                //Uri uri = new Uri(tempJPEG, UriKind.Relative);
                //sri = Application.GetResourceStream(uri);

                //BitmapImage bitmap = new BitmapImage();
                //bitmap.SetSource(sri.Stream);
                WriteableBitmap wb = new WriteableBitmap(bitmap);

                // Encode WriteableBitmap object to a JPEG stream.
                Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

                //wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
                fileStream.Close();
            }
        }