Beispiel #1
0
        /// <summary>
        /// Save the stream into a PDF file with provided file name.
        /// </summary>
        public async static void Save(string filename, MemoryStream stream)
        {
            StorageFile stFile;

            //Get process windows handle to open the dialog in application process.
            IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

            if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
            {
                //Create file save picker to save a PDF file.
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.DefaultFileExtension = ".pdf";
                savePicker.SuggestedFileName    = filename;
                savePicker.FileTypeChoices.Add("PDF document files", new List <string>()
                {
                    ".pdf"
                });
                WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle);
                stFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = ApplicationData.Current.LocalFolder;
                stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            }

            if (stFile != null)
            {
                using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    //Write compressed data from memory to file
                    using (Stream outstream = zipStream.AsStreamForWrite())
                    {
                        outstream.SetLength(0);
                        //Save the stream as PDF file.
                        byte[] buffer = stream.ToArray();
                        outstream.Write(buffer, 0, buffer.Length);
                        outstream.Flush();
                    }
                }

                //Create message dialog box.
                MessageDialog msgDialog = new MessageDialog("Do you want to view the document?", "File created");
                UICommand     yesCmd    = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);

                WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle);

                //Showing a dialog box.
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd.Label == yesCmd.Label)
                {
                    // Launch the saved PDF file.
                    await Windows.System.Launcher.LaunchFileAsync(stFile);
                }
            }
        }
Beispiel #2
0
        public async Task SaveAsync(T Obj)
        {
            try
            {
                if (Obj != null)
                {
                    StorageFile   file   = null;
                    StorageFolder folder = GetFolder(storageType);

                    if (string.IsNullOrEmpty(fileName))
                    {
                        fileName = FileName(Obj);
                    }

                    file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                    IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                    Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result;
                    serializer.Serialize(outStream, Obj);

                    outStream.Dispose();
                }
            }
            catch (System.Exception ex)
            {
            }
        }
        private async Task <StorageFile> SaveContract(Stream stream)
        {
            stream.Position = 0;

            StorageFile stFile;

            FileSavePicker fileSavePicker = new FileSavePicker();

            fileSavePicker.SuggestedFileName = "SFPdfRTL";
            fileSavePicker.FileTypeChoices.Add(".pdf", new List <string> {
                ".pdf"
            });
            fileSavePicker.SuggestedStartLocation = PickerLocationId.Desktop;

            stFile = await fileSavePicker.PickSaveFileAsync();

            if (stFile != null)
            {
                IRandomAccessStream fileStream = await stFile.OpenAsync(FileAccessMode.ReadWrite);

                Stream st = fileStream.AsStreamForWrite();
                st.SetLength(0);
                st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length);
                st.Flush();
                st.Dispose();
                fileStream.Dispose();
            }

            return(stFile);
        }
        //保存图片到本地
        private async void savePictureAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            FileSavePicker fileSavePicker = new FileSavePicker();

            fileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileSavePicker.FileTypeChoices.Add("Picture", new List <string>()
            {
                ".jpg"
            });
            fileSavePicker.SuggestedFileName = "image";

            var outputFile = await fileSavePicker.PickSaveFileAsync();

            if (outputFile == null)
            {
                // The user cancelled the picking operation
                return;
            }
            //请求流文件保存即可保存高清图
            HttpClient client = new HttpClient();
            Stream     Stream = await client.GetStreamAsync(new Uri(url));

            using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await Stream.CopyToAsync(stream.AsStreamForWrite());
            }
        }
Beispiel #5
0
        /// <inheritdoc/>
        public async Task <string> WriteFileAsync(Stream stream, string nameWithExt, string localDirName = null)
        {
            StorageFolder dir;

            if (string.IsNullOrWhiteSpace(localDirName))
            {
                dir = ApplicationData.Current.LocalFolder;
            }
            else
            {
                dir = await ApplicationData.Current.LocalFolder.CreateFolderAsync(
                    localDirName,
                    CreationCollisionOption.OpenIfExists);
            }

            StorageFile storageFile = await dir.CreateFileAsync(
                nameWithExt,
                CreationCollisionOption.ReplaceExisting);

            using IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

            await stream.CopyToAsync(fileStream.AsStreamForWrite());

            await fileStream.FlushAsync();

            return(storageFile.Path);
        }
        /// <summary>
        /// Store an instance of T to Windows.Storage.ApplicationData with a specified handle.
        /// Specification of a handle supports storage and deletion of different instances of T.
        /// </summary>
        /// <param name="Obj">Object to be saved</param>
        /// <param name="Handle">User-defined handle for the stored object</param>
        public async Task SaveAsync(T Obj, string Handle)
        {
            if (Obj == null)
            {
                throw new ArgumentNullException("Obj");
            }
            if (Handle == null)
            {
                throw new ArgumentNullException("Handle");
            }

            StorageFile   file     = null;
            string        fileName = Handle;
            StorageFolder folder   = GetFolder(storageType);

            file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);

            using (Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result)
            {
                serializer.Serialize(outStream, Obj);
                await outStream.FlushAsync();
            }
        }
Beispiel #7
0
        public async void UpdateAndClose(StorageFile storageFile, object obj)
        {
            using (IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var binFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                using (Stream streamNew = stream.AsStreamForWrite())
                {
                    if (obj is List <LibaryItem> )
                    {
                        binFormatter.Serialize(streamNew, ListOfItems);
                    }
                    else
                    {
                        throw new ArgumentException("invalid list");
                    }

                    if (obj is List <Employee> )
                    {
                        binFormatter.Serialize(streamNew, ListOfEmployees);
                    }
                    else
                    {
                        throw new ArgumentException("invalid list");
                    }
                }
            }
        }
        public async void PrintPDF(Memo memo)
        {
            Reports = new Reports(memo);
            //var stream = new InMemoryRandomAccessStream();
            //FileSavePicker fileSavePicker = new FileSavePicker();
            WriterFormat format = WriterFormat.PDF;

            //fileSavePicker.SuggestedFileName = "ExportReport";
            //var savedItem = await fileSavePicker.PickSaveFileAsync();

            //if (savedItem != null)
            //

            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;

            Windows.Storage.StorageFile savedItem =
                await storageFolder.CreateFileAsync("sample.pdf",
                                                    Windows.Storage.CreationCollisionOption.ReplaceExisting);

            //var savedItem = await FileSavePicker.PickSaveFileAsync();
            MemoryStream exportFileStream = new MemoryStream();

            Assembly assembly = typeof(HomePage).GetTypeInfo().Assembly;
            // Ensure the report loaction and application name.
            Stream reportStream = assembly.GetManifestResourceStream("UwpApp.Report.Inv.rdlc");

            BoldReports.UI.Xaml.ReportDataSourceCollection datas = new BoldReports.UI.Xaml.ReportDataSourceCollection();
            datas.Add(new BoldReports.UI.Xaml.ReportDataSource {
                Name = "PatientInfo", Value = Reports.LoadReport()
            });
            datas.Add(new BoldReports.UI.Xaml.ReportDataSource {
                Name = "MemoDetails", Value = Reports.loadmemodetail()
            });



            ReportWriter writer = new ReportWriter(reportStream, datas);

            writer.ExportMode = ExportMode.Local;
            await writer.SaveASync(exportFileStream, format);



            try
            {
                using (IRandomAccessStream stream = await savedItem.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // Write compressed data from memory to file
                    using (Stream outstream = stream.AsStreamForWrite())
                    {
                        byte[] buffer = exportFileStream.ToArray();
                        outstream.Write(buffer, 0, buffer.Length);
                        outstream.Flush();
                    }
                }
                exportFileStream.Dispose();
            }
            catch { }
        }
Beispiel #9
0
        /// <summary>
        /// Saves all data that this repository has
        /// </summary>
        /// <param name="rootFolder">Folder in which to save the data</param>
        public async Task Save(StorageFolder rootFolder)
        {
            StorageFolder modelFolder = await GetFolder(rootFolder);

            // If all data was deleted then delete all the files
            if (modelProperty().Count == 0)
            {
                // Create a new folder for this model, deleting the old one while it does
                modelFolder = await rootFolder.CreateFolderAsync(ModelName + "s", CreationCollisionOption.ReplaceExisting);
            }

            // Loop each instance in the list
            foreach (T model in modelProperty())
            {
                // Create an XmlSerializer for serializing the data
                XmlSerializer xmlSerializer = new XmlSerializer(model.GetType());
                // Create a file for the model
                // We replace existing files so that it overwrites old data
                StorageFile file = await modelFolder.CreateFileAsync(model.ID.ToString(), CreationCollisionOption.ReplaceExisting);

                // A random access stream is used to push data to the file
                IRandomAccessStream fileRandomAccessStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                // Used to disposing and flushing data which helps for memory conservation
                IOutputStream fileOutputStream = fileRandomAccessStream.GetOutputStreamAt(0);
                // Serialize the data to the file
                xmlSerializer.Serialize(fileRandomAccessStream.AsStreamForWrite(), model);
                // Dispose of and flush the file streams (Do flush asynchronously so it doesn't jam the thread)
                fileRandomAccessStream.Dispose();
                await fileOutputStream.FlushAsync();

                fileOutputStream.Dispose();
            }
        }
Beispiel #10
0
        public async Task <bool> SaveAsync(T Obj, string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                if (Obj != null)
                {
                    StorageFile   file   = null;
                    StorageFolder folder = GetFolder(storageType);
                    file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

                    using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        using (Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result)
                        {
                            serializer.Serialize(outStream, Obj);
                            outStream.Dispose();
                            return(true);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(false);
        }
Beispiel #11
0
        public static async Task <Boolean> SerializeToXmlFile <T>(string fileName, T serializationSource)
        {
            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                    fileName, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));

                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent          = true;
                    settings.NewLineHandling = NewLineHandling.Entitize;
                    XmlWriter writer = XmlWriter.Create(stream.AsStreamForWrite(), settings);
                    var       ser    = new XmlSerializer(typeof(T));
                    ser.Serialize(writer, serializationSource);
                    return(true);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return(false);
            }
        }
Beispiel #12
0
        public static async void Save(string filename)
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                Stream            s        = writeStream.AsStreamForWrite();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Async = true;
                using (XmlWriter writer = XmlWriter.Create(s, settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Problems");

                    foreach (TrafficProblem problem in Problems)
                    {
                        writer.WriteStartElement("Problem");

                        writer.WriteElementString("Reason", problem.Reason);

                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                    writer.WriteEndDocument();

                    await writer.FlushAsync();
                }
            }
        }
        public async void WriteToXmlFileAsync(Person person)
        {
            StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
            StorageFile   storageFile   = await storageFolder.GetFileAsync("xmluppgift_1.xml");

            using (IRandomAccessStream streamWriter = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                Stream stream = streamWriter.AsStreamForWrite();

                XmlWriterSettings settings = new XmlWriterSettings()
                {
                    Indent      = true,
                    IndentChars = (" "),
                    CloseOutput = true
                };

                using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
                {
                    xmlWriter.WriteStartElement($"person");

                    xmlWriter.WriteElementString($"FirstName", $"{ person.FirstName}");
                    xmlWriter.WriteElementString($"LastName", $"{ person.LastName}");
                    xmlWriter.WriteElementString($"Age", $"{ person.Age}");
                    xmlWriter.WriteElementString($"Email", $"{ person.Email}");

                    xmlWriter.Flush();
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// Get file stream from bytes array
        /// </summary>
        /// <param name="bytes">Serialized stream</param>
        /// <returns>File random access stream</returns>
        private async Task <IRandomAccessStream> bytesToStream(byte[] bytes)
        {
            StorageFile         file;
            IRandomAccessStream filestream = null;

            try
            {
                file = await KnownFolders.MusicLibrary.GetFileAsync("RecievedFile");

                await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                try
                {
                    file = await KnownFolders.MusicLibrary.CreateFileAsync("RecievedFile");

                    filestream = await file.OpenAsync(FileAccessMode.ReadWrite);

                    await filestream.AsStreamForWrite().WriteAsync(bytes, 0, bytes.Length);
                }
                catch (Exception)
                {
                    //something goes wrong
                }
            }

            return(filestream);
        }
Beispiel #15
0
        private async void GenerateStream()
        {
            _accessStream = await _file.OpenAsync(FileAccessMode.ReadWrite);

            _classicStream = _accessStream.AsStreamForWrite();
            _streamWriter  = new StreamWriter(_classicStream, _encoding);
        }
        private async Task DoWork(IBackgroundTaskInstance taskInstance)
        {
            var settings = ApplicationData.Current.RoamingSettings;

            string text = "";

            foreach (var item in ApplicationData.Current.RoamingSettings.Values)
            {
                text += item.ToString();
            }
            string typeFile = (string)settings.Values["typeFile"];

            ApplicationData.Current.RoamingSettings.Values.Clear();
            StorageFile   stFile;
            StorageFolder localFolder = Windows.Storage.ApplicationData.Current.TemporaryFolder;

            stFile = await localFolder.CreateFileAsync("temp.txt", CreationCollisionOption.ReplaceExisting);

            if (stFile != null)
            {
                using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (Stream outstream = zipStream.AsStreamForWrite())
                    {
                        byte[] buffer = System.Text.Encoding.Default.GetBytes(text);
                        outstream.Write(buffer, 0, buffer.Length);
                        outstream.Flush();
                    }
                }
            }
        }
        public WindowsUniversalFileStream(string fileName, StorageFolder directory, FileAccessMode mode, CreationCollisionOption collisionOptions, StorageOpenOptions openOptions, int length = 1024 * 80, int writeBufferSize = 1024 * 80, int readBufferSize = 1024 * 80)
        {
            if (fileName == null || fileName == string.Empty)
            {
                throw new ArgumentNullException("path");
            }

            Directory        = directory;
            FileName         = fileName;
            Mode             = mode;
            CollisionOptions = collisionOptions;
            OpenOptions      = openOptions;

            WriteBufferSize = writeBufferSize;
            ReadBufferSize  = readBufferSize;

            RandomAccessStream = Directory.CreateFileAsync(FileName, collisionOptions).AsTask().Result.OpenAsync(mode, openOptions).AsTask().Result;
            ReadStream         = RandomAccessStream.AsStreamForRead(ReadBufferSize);
            ReadStream.SetLength(length);

            if (mode == FileAccessMode.ReadWrite)
            {
                WriteStream = RandomAccessStream.AsStreamForWrite(WriteBufferSize);
            }
        }
Beispiel #18
0
        private async void button2_Click(object sender, RoutedEventArgs e)
        {
            //Create file open picker and set the .pdf file type.
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.FileTypeFilter.Add(".pdf");

            //Get process windows handle to open the dialog in application process.
            IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

            WinRT.Interop.InitializeWithWindow.Initialize(openPicker, windowHandle);

            //Pick the single file.
            StorageFile stFile = await openPicker.PickSingleFileAsync();

            if (stFile != null)
            {
                //Get the file name and update the file name in textbox.
                SecondPdf.Text = stFile.Name;

                //Read the PDF file as file stream.
                IRandomAccessStream fileStream = await stFile.OpenAsync(FileAccessMode.ReadWrite);

                secondDocumentStream = fileStream.AsStreamForWrite();
            }
        }
Beispiel #19
0
        public static async Task <StorageFile> WriteableBitmapToStorageFile(ushort[,] image, bool isScaleValues, List <KeyValuePair <string, string> > metadata)
        {
            //Setup image maxVal.
            var   imgHeight = image.GetLength(0);
            var   imgWidth  = image.GetLength(1);
            float maxVal    = 1;

            if (isScaleValues)
            {
                for (int i = 0; i < imgHeight; i++)
                {
                    for (int j = 0; j < imgWidth; j++)
                    {
                        if (maxVal < image[i, j])
                        {
                            maxVal = image[i, j];
                        }
                    }
                }
            }

            string FileName = "MyFile.png";
            var    file     =
                await
                Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName,
                                                                                        CreationCollisionOption.GenerateUniqueName);

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                ImageInfo   imgInfo = new ImageInfo(imgWidth, imgHeight, 16, false, true, false);
                PngWriter   wrt     = new PngWriter(stream.AsStreamForWrite(), imgInfo);
                PngMetadata da      = wrt.GetMetadata();
                foreach (var item in metadata)
                {
                    if (item.Value != null)
                    {
                        da.SetText(item.Key, item.Value);
                    }
                }
                ImageLines imLines = new ImageLines(imgInfo, ImageLine.ESampleType.INT, false, 0, imgHeight, 1);
                for (int i = 0; i < imLines.ImgInfo.Rows; i++)
                {
                    for (int j = 0; j < imLines.ImgInfo.Cols; j++)
                    {
                        if (isScaleValues)
                        {
                            imLines.Scanlines[i][j] = (ushort)(ushort.MaxValue * (double)image[i, j] / maxVal);
                        }
                        else
                        {
                            imLines.Scanlines[i][j] = image[i, j];
                        }
                    }
                }
                wrt.WriteRowsInt(imLines.Scanlines);
                wrt.End();
            }
            return(file);
        }
        /// <summary>
        /// Unzips ZipArchiveEntry asynchronously.
        /// </summary>
        /// <param name="entry">The entry which needs to be unzipped</param>
        /// <param name="filePath">The entry's full name</param>
        /// <param name="unzipFolder">The unzip folder</param>
        /// <returns></returns>
        private static async Task UnzipZipArchiveEntryAsync(ZipArchiveEntry entry, string filePath, StorageFolder unzipFolder)
        {
            if (IfPathContainDirectory(filePath))
            {
                // Create sub folder
                string subFolderName = Path.GetDirectoryName(filePath);

                bool isSubFolderExist = await IfFolderExistsAsync(unzipFolder, subFolderName);

                StorageFolder subFolder;

                if (!isSubFolderExist)
                {
                    // Create the sub folder.
                    subFolder =
                        await unzipFolder.CreateFolderAsync(subFolderName, CreationCollisionOption.ReplaceExisting);
                }
                else
                {
                    // Just get the folder.
                    subFolder =
                        await unzipFolder.GetFolderAsync(subFolderName);
                }

                // All sub folders have been created yet. Just pass the file name to the Unzip function.
                string newFilePath = Path.GetFileName(filePath);

                if (!string.IsNullOrEmpty(newFilePath))
                {
                    // Unzip file iteratively.
                    await UnzipZipArchiveEntryAsync(entry, newFilePath, subFolder);
                }
            }
            else
            {
                // Read uncompressed contents
                using (Stream entryStream = entry.Open())
                {
                    byte[] buffer = new byte[entry.Length];
                    entryStream.Read(buffer, 0, buffer.Length);

                    // Create a file to store the contents
                    StorageFile uncompressedFile = await unzipFolder.CreateFileAsync
                                                       (entry.Name, CreationCollisionOption.ReplaceExisting);

                    // Store the contents
                    using (IRandomAccessStream uncompressedFileStream =
                               await uncompressedFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        using (Stream outstream = uncompressedFileStream.AsStreamForWrite())
                        {
                            outstream.Write(buffer, 0, buffer.Length);
                            outstream.Flush();
                        }
                    }
                }
            }
        }
Beispiel #21
0
 public async Task SaveAsXmlAsync <T>(storage.StorageFile file) where T : VMBase
 {
     xmlser.XmlSerializer ser = new xmlser.XmlSerializer(typeof(T));
     using (IRandomAccessStream myFileStream = await file.OpenAsync(storage.FileAccessMode.ReadWrite))
     {
         Stream wStream = myFileStream.AsStreamForWrite();
         ser.Serialize(wStream, this);
     }
 }
Beispiel #22
0
        /// <summary>
        /// method to compress files
        /// </summary>
        public async void Compress()
        {
            // Retrieve files to compress


            // Created new file to store compressed files
            //This will create a file under the selected folder in the name “Compressed.zip”
            StorageFile zipFile = await SelectedFolder.CreateFileAsync("Compressed.zip", CreationCollisionOption.ReplaceExisting);

            // Create stream to compress files in memory (ZipArchive can't stream to an IRandomAccessStream, see
            // http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/62541424-ba7d-43d3-9585-1fe53dc7d9e2
            // for details on this issue)
            using (MemoryStream zipMemoryStream = new MemoryStream())
            {
                InProgress = true;
                // Create zip archive
                using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Create))
                {
                    // For each file to compress...
                    foreach (StorageFile fileToCompress in filesToCompress)
                    {
                        BasicProperties fileProp = await fileToCompress.GetBasicPropertiesAsync();

                        if (fileProp.Size > 0)
                        {
                            //Read the contents of the file
                            byte[] buffer = WindowsRuntimeBufferExtensions.ToArray(await FileIO.ReadBufferAsync(fileToCompress));

                            string fileEntry = fileToCompress.Path.Replace(zipFile.Path.Replace(zipFile.Name, string.Empty), string.Empty);
                            // Create a zip archive entry
                            ZipArchiveEntry entry = zipArchive.CreateEntry(fileEntry, CompressionLevelSelected);

                            // And write the contents to it
                            using (Stream entryStream = entry.Open())
                            {
                                await entryStream.WriteAsync(buffer, 0, buffer.Length);
                            }
                        }
                    }
                }

                using (IRandomAccessStream zipStream = await zipFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // Write compressed data from memory to file
                    using (Stream outstream = zipStream.AsStreamForWrite())
                    {
                        byte[] buffer = zipMemoryStream.ToArray();
                        outstream.Write(buffer, 0, buffer.Length);
                        outstream.Flush();
                    }
                }

                InProgress    = false;
                StatusMessage = "Files Zipped...";
            }
        }
Beispiel #23
0
        public void SetScoreData(string data)
        {
            StorageFile         file        = ApplicationData.Current.LocalFolder.CreateFileAsync(scoreFilePath, CreationCollisionOption.ReplaceExisting).GetResults();
            IRandomAccessStream writeStream = file.OpenAsync(FileAccessMode.ReadWrite).GetResults();

            using (Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result)
                using (var tw = new StreamWriter(outStream))
                {
                    tw.WriteAsync(data).Wait();
                }
        }
Beispiel #24
0
 public async Task WriteExcuseAsync()
 {
     using (IRandomAccessStream stream = await excuseFile.OpenAsync(FileAccessMode.ReadWrite))
         using (Stream outputStream = stream.AsStreamForWrite())
         {
             DataContractSerializer serializer = new DataContractSerializer(typeof(Excuse));
             serializer.WriteObject(outputStream, CurrentExcuse);
         }
     await new MessageDialog("Excuse written to " + excuseFile.Name).ShowAsync();
     await UpdateFileDateAsync();
 }
Beispiel #25
0
        public static async Task saveAllSettingsAsync(StorageFile file, ApplicationSettings settings)
        {
            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

            string       str    = JsonConvert.SerializeObject((ApplicationSettings)settings);
            StreamWriter writer = new StreamWriter(stream.AsStreamForWrite());

            writer.Write(str);
            writer.Flush();
            writer.Close();
        }
        private static async Task WriteToVoiceCommandDefinitionAsync(IEnumerable <Contact> contacts)
        {
            try
            {
                //create file in public folder
                StorageFolder storageFolder          = ApplicationData.Current.LocalFolder;
                StorageFile   publicVoiceCommandFile = await storageFolder.CreateFileAsync("VoiceCommandDefinition.xml", CreationCollisionOption.ReplaceExisting);

                Uri         uri = new Uri("ms-appx:///Common/Cortana/VoiceCommandDefinition.xml");
                StorageFile privateVoiceCommandFile = await StorageFile.GetFileFromApplicationUriAsync(uri);

                string stringData = await FileIO.ReadTextAsync(privateVoiceCommandFile);

                //write sring to created file
                await FileIO.WriteTextAsync(publicVoiceCommandFile, stringData);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("error: " + ex);
            }

            //StorageFile myFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Cortana/VoiceCommandDefinition.xml");
            StorageFile vcf = await ApplicationData.Current.LocalFolder.GetFileAsync("VoiceCommandDefinition.xml");

            using (IRandomAccessStream writeStream = await vcf.OpenAsync(FileAccessMode.ReadWrite))
            {
                XNamespace defaultNs = "http://schemas.microsoft.com/voicecommands/1.2";

                // convert IRandomAccessStream to IO.Stream
                Stream s = writeStream.AsStreamForWrite();

                //xml
                XDocument document = XDocument.Load(s);
                var       element  = document.Root.Elements().FirstOrDefault();
                element.Add(new XElement(defaultNs + "PhraseList", new XAttribute("Label", "nutzer")));

                var PhraseList = element.Element(defaultNs + "PhraseList");

                foreach (var item in contacts)
                {
                    PhraseList.Add(new XElement("Item", item.Name));
                }

                s.Seek(0, SeekOrigin.Begin);
                document.Save(s);
            }

            ////get asets folder
            //StorageFolder appInstalledFolder = Package.Current.InstalledLocation;
            //StorageFolder assetsFolder = await appInstalledFolder.GetFolderAsync("Cortana");

            ////move file from public folder to assets
            //await vcf.MoveAsync(assetsFolder, "VoiceCommandDefinition.xml", NameCollisionOption.ReplaceExisting);
        }
Beispiel #27
0
 public static async void Serialize <T>(IStorageFile file, T obj)
 {
     using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
     {
         using (StreamWriter writer = new StreamWriter(stream.AsStreamForWrite(), Encoding.UTF8))
         {
             XmlSerializer xs = new XmlSerializer(typeof(T));
             xs.Serialize(writer, obj);
         }
     }
 }
        public async void SaveGame(object sender, RoutedEventArgs e)
        {
            game.Time = DateTime.Now;
            StorageFile f = await def.GetFileAsync("sgd.dat");

            IRandomAccessStream iras = await f?.OpenAsync(FileAccessMode.ReadWrite);

            iras.Size = 0;
            //using (Stream s = Task.Run(() => iras.AsStreamForWrite()).Result) Serializer.Serialize(s, game);
            using (Stream s = Task.Run(() => iras.AsStreamForWrite()).Result) serializer.Serialize(s, game);
            SaveCard.Begin();
        }
Beispiel #29
0
        async Task <StorageFile> Save(MemoryStream stream, string filename)
        {
            stream.Position = 0;

            StorageFile stFile;

            //if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))

            //{

            //    FileSavePicker savePicker = new FileSavePicker();

            //    savePicker.DefaultFileExtension = ".docx";

            //    savePicker.SuggestedFileName = filename;

            //    savePicker.FileTypeChoices.Add("Word Documents", new List<string>() { ".docx" });

            //    stFile = await savePicker.PickSaveFileAsync();

            //}

            //else

            //{

            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

            stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            //}
            if (stFile != null)

            {
                using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))

                {
                    // Write compressed data from memory to file

                    using (Stream outstream = zipStream.AsStreamForWrite())

                    {
                        byte[] buffer = stream.ToArray();

                        outstream.Write(buffer, 0, buffer.Length);

                        outstream.Flush();
                    }
                }
            }
            return(stFile);
        }
        private async void writeToXml(SavedData savedData, string fileName)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(savedData.GetType());
            StorageFile   file          = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(writeStream.AsStreamForWrite()))
                {
                    xmlSerializer.Serialize(xmlWriter, savedData);
                }
            }
        }