Exemplo n.º 1
0
    public static async Task <IBook> GetBookFromFile(IStorageFile file, BookType type, Windows.UI.Xaml.XamlRoot xamlRoot = null, bool skipPasswordEntryPdf = false)
    {
        switch (type)
        {
        case BookType.Epub: goto Epub;

        case BookType.Zip: goto Zip;

        case BookType.Rar: goto SharpCompress;

        case BookType.SevenZip: goto SharpCompress;

        case BookType.Pdf: goto Pdf;
        }


        Pdf :;
        return(await GetBookPdf(await file.OpenReadAsync(), file.Name, xamlRoot, skipPasswordEntryPdf));

        Zip :;
        return(await GetBookZip((await file.OpenReadAsync()).AsStream()));

        SharpCompress :;
        return(await GetBookSharpCompress((await file.OpenReadAsync()).AsStream()));

        Epub :;
        {
            return(new BookEpub(file));
        }
    }
Exemplo n.º 2
0
        /// <summary>
        /// Sets the given file as the source media to play.
        /// </summary>
        /// <param name="fileToPlay">The file to play.</param>
        public async void SetSource(IStorageFile fileToPlay)
        {
            if (fileToPlay != null)
            {
                var stream = await fileToPlay.OpenReadAsync();

                _mediaElement.SetSource(stream, fileToPlay.ContentType);

                // Other "Set Source" alternatives inlcude:

                // Setting the source to a URI:
                //_mediaElement.Source = new Uri("ms-appx:///Assets/Sample.wmv");

                // Using Set Media Stream Source:
                //var mediaStreamSource =
                //    new MediaStreamSource(new VideoStreamDescriptor(VideoEncodingProperties.CreateH264()),
                //        new AudioStreamDescriptor(AudioEncodingProperties.CreateMp3(48000, 2, 32)));
                //mediaStreamSource.SampleRequested += (sender, args) =>
                //                                     {
                //                                         if (args.Request.StreamDescriptor is AudioStreamDescriptor)
                //                                         {
                //                                             var sample = new MediaStreamSample();
                //                                             sample.Buffer.
                //                                         }

                //                                     }
                //_mediaElement.SetMediaStreamSource(mediaStreamSource);
            }
        }
Exemplo n.º 3
0
 private static async Task <XDocument> LoadXDocument(IStorageFile file)
 {
     using (var stream = await file.OpenReadAsync())
     {
         return(XDocument.Load(stream.AsStreamForRead()));
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// 读取本地文件夹根目录的文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>读取文件的内容</returns>
        public static async Task <string> ReadFileAsync(string fileName)
        {
            string text;

            try
            {
                // 获取存储数据的文件夹
                IStorageFolder applicationFolder = await GetDataFolder();

                // 根据文件名获取文件夹里面的文件
                IStorageFile storageFile = await applicationFolder.GetFileAsync(fileName);

                // 打开文件获取文件的数据流
                IRandomAccessStream accessStream = await storageFile.OpenReadAsync();

                // 使用StreamReader读取文件的内容,需要将IRandomAccessStream对象转化为Stream对象来初始化StreamReader对象
                using (StreamReader streamReader = new StreamReader(accessStream.AsStreamForRead((int)accessStream.Size)))
                {
                    text = streamReader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                text = "文件读取错误:" + e.Message;
            }
            return(text);
        }
Exemplo n.º 5
0
        private async Task LoadImageAndDecode(IStorageFile file)
        {
            using (var stream = await file.OpenReadAsync())
            {
                var bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(stream);

                qrBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
                stream.Seek(0);
                await qrBitmap.SetSourceAsync(stream);

                var result = qrReader.Decode(qrBitmap);

                QRCodeImage.Source  = qrBitmap;
                QRCodeImage.Stretch = Stretch.Uniform;

                if (result != null)
                {
                    QRTextBox.TextChanged -= QRTextBox_TextChanged;
                    QRTextBox.Text         = result.Text;
                    QRTextBox.TextChanged += QRTextBox_TextChanged;
                }
                else
                {
                    var dialog = new MessageDialog("No QRCode detected");
                    await dialog.ShowAsync();
                }
            }
        }
Exemplo n.º 6
0
        public static async Task <T> ReadObjectFromFile <T>(this IStorageFile file) where T : class
        {
            T result = default(T);

            if (file != null)
            {
                using (var randomStream = await file.OpenReadAsync())
                {
                    if (randomStream.Size > 0)
                    {
                        var js = new DataContractJsonSerializer(typeof(T));

                        try
                        {
                            result = js.ReadObject(randomStream.AsStream()) as T;
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                }
            }

            return(result);
        }
Exemplo n.º 7
0
        private static async Task <ZipArchiveEntry> DoCreateEntryFromFile(ZipArchive destination, IStorageFile sourceFile, string entryName, CompressionLevel?compressionLevel)
        {
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }
            if (sourceFile == null)
            {
                throw new ArgumentNullException("sourceFile");
            }
            if (entryName == null)
            {
                throw new ArgumentNullException("entryName");
            }
            using (Stream stream = (await sourceFile.OpenReadAsync()).AsStream())
            {
                ZipArchiveEntry zipArchiveEntry = compressionLevel.HasValue ? destination.CreateEntry(entryName, compressionLevel.Value) : destination.CreateEntry(entryName);

                var props = await sourceFile.GetBasicPropertiesAsync();

                DateTime dateTime = props.DateModified.UtcDateTime;
                if (dateTime.Year < 1980 || dateTime.Year > 2107)
                {
                    dateTime = new DateTime(1980, 1, 1, 0, 0, 0);
                }
                zipArchiveEntry.LastWriteTime = (DateTimeOffset)dateTime;
                using (Stream destination1 = zipArchiveEntry.Open())
                {
                    await stream.CopyToAsync(destination1);
                }
                return(zipArchiveEntry);
            }
        }
Exemplo n.º 8
0
        private static async Task<Uri> GenerateThumbnail(IStorageFile file)
        {
            using (var fileStream = await file.OpenReadAsync())
            {
                // decode the file using the built-in image decoder
                var decoder = await BitmapDecoder.CreateAsync(fileStream);

                // create the output file for the thumbnail
                var thumbFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                    string.Format("thumbnail{0}", file.FileType),
                    CreationCollisionOption.GenerateUniqueName);

                // create a stream for the output file
                using (var outputStream = await thumbFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // create an encoder from the existing decoder and set the scaled height
                    // and width 
                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(
                        outputStream,
                        decoder);
                    encoder.BitmapTransform.ScaledHeight = 100;
                    encoder.BitmapTransform.ScaledWidth = 100;
                    await encoder.FlushAsync();
                }

                // create the URL
                var storageUrl = string.Format(URI_LOCAL, thumbFile.Name);

                // return it
                return new Uri(storageUrl, UriKind.Absolute);
            }
        }
        public static async Task <SafeWrapperResult> CopyFileAsync(IStorageFile source, IStorageFile destination, Action <float> progressReportDelegate, CancellationToken cancellationToken)
        {
            long fileSize = await StorageHelpers.GetFileSize(source);

            byte[]            buffer = new byte[Constants.FileSystem.COPY_FILE_BUFFER_SIZE];
            SafeWrapperResult result = SafeWrapperResult.S_SUCCESS;

            using (Stream sourceStream = (await source.OpenReadAsync()).AsStreamForRead())
            {
                using (Stream destinationStream = (await destination.OpenAsync(FileAccessMode.ReadWrite)).AsStreamForWrite())
                {
                    long bytesTransferred = 0L;
                    int  currentBlockSize = 0;

                    while ((currentBlockSize = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        bytesTransferred += currentBlockSize;
                        float percentage = (float)bytesTransferred * 100.0f / (float)fileSize;

                        await destinationStream.WriteAsync(buffer, 0, currentBlockSize);

                        progressReportDelegate?.Invoke(percentage);

                        if (cancellationToken.IsCancellationRequested)
                        {
                            // TODO: Delete copied file there
                            result = SafeWrapperResult.S_CANCEL;
                            break;
                        }
                    }
                }
            }

            return(result);
        }
        public void ReadAllText(string filename, Action <string> completed)
        {
            StorageFolder localFolder =
                ApplicationData.Current.LocalFolder;
            IAsyncOperation <StorageFile> createOp =
                localFolder.GetFileAsync(filename);

            createOp.Completed = (asyncInfo1, asyncStatus1) =>
            {
                IStorageFile storageFile = asyncInfo1.GetResults();
                IAsyncOperation <IRandomAccessStreamWithContentType>
                openOp = storageFile.OpenReadAsync();
                openOp.Completed = (asyncInfo2, asyncStatus2) =>
                {
                    IRandomAccessStream stream     = asyncInfo2.GetResults();
                    DataReader          dataReader = new DataReader(stream);
                    uint length = (uint)stream.Size;
                    DataReaderLoadOperation loadOp =
                        dataReader.LoadAsync(length);
                    loadOp.Completed = (asyncInfo3, asyncStatus3) =>
                    {
                        string text = dataReader.ReadString(length);
                        dataReader.Dispose();
                        completed(text);
                    };
                };
            };
        }
Exemplo n.º 11
0
 /// <summary>
 /// Reads the contents of the specified file and returns a byte array.
 /// </summary>
 /// <param name="file">The file to read.</param>
 /// <returns>When this method completes, it returns an array of bytes that represents the contents of the file.</returns>
 public static async Task <byte[]> ReadBytesAsync(this IStorageFile file)
 {
     using (var stream = await file.OpenReadAsync())
     {
         return(await stream.ToBytesAsync());
     }
 }
Exemplo n.º 12
0
 private static async Task <bool> CheckAccess(IStorageFile file)
 {
     return(await SafetyExtensions.IgnoreExceptions(async() =>
     {
         using var stream = await file.OpenReadAsync();
         return CheckAccess(stream.AsStream());
     }));
 }
        public async Task <bool> UploadImageAsync(IStorageFile imageFile, IList <string> tags = null)
        {
            var stream = await imageFile.OpenReadAsync();

            //var tagIds = (from t in tags select t.Id.ToString()).ToList();
            var result = await _trainingApi.CreateImagesFromDataWithHttpMessagesAsync(_currentProject.Id, stream.AsStream(), tags);

            return(true);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Resource management is not proper here. Suggest an improvement.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task SetSource(IStorageFile file)
        {
            var stream = await file.OpenReadAsync();

            sourceStream = stream;
            await StoreUtil.OnUiThread(() => {
                Player.SetSource(stream, stream.ContentType);
            });
        }
Exemplo n.º 15
0
        public async Task AddKeyFile(IStorageFile file)
        {
            KeyfileName = file.Name;
            using (var input = await file.OpenReadAsync())
                await _password.AddKeyFile(input);

            NotifyOfPropertyChange(() => CanOpenDatabase);
            NotifyOfPropertyChange(() => CanClearKeyfile);
            NotifyOfPropertyChange(() => KeyfileGroupVisibility);
        }
Exemplo n.º 16
0
        private async Task <City> GetStoredCityAsync()
        {
            var fileStream = await _storedFile.OpenReadAsync();

            var streamReader = new StreamReader(fileStream.AsStream());

            string json = streamReader.ReadToEnd();
            var    city = JsonConvert.DeserializeObject <City>(json);

            return(city);
        }
Exemplo n.º 17
0
        private async static Task<byte[]> ReadStorageFileToByteBuffer(IStorageFile storageFile)
        {
            IRandomAccessStream accessStream = await storageFile.OpenReadAsync();
            byte[] content = null;

            using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
            {
                content = new byte[stream.Length];
                await stream.ReadAsync(content, 0, (int)stream.Length);
            }

            return content;
        }
 private static async Task CopyFileIntoIsoStore(IStorageFile sourceFile)
 {
     using (var s = await sourceFile.OpenReadAsync())
     using (var dr = new DataReader(s))
     using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
     using (var targetFile = isoStore.CreateFile(sourceFile.Name))
     {
         var data = new byte[s.Size];
         await dr.LoadAsync((uint)s.Size);
         dr.ReadBytes(data);
         targetFile.Write(data, 0, data.Length);
     }
 }
Exemplo n.º 19
0
        public static async Task <Stream> OpenStreamForReadAsync(this IStorageFile windowsRuntimeFile)
        {
            if (windowsRuntimeFile is StorageFile file)
            {
                return(await file.OpenStream(CancellationToken.None, FileAccessMode.Read, StorageOpenOptions.None));
            }
            else
            {
                var raStream = await windowsRuntimeFile.OpenReadAsync();

                return(raStream.AsStreamForRead());
            }
        }
Exemplo n.º 20
0
        private async Task <(string, IMediaInfo, DateTimeOffset)> ReadMediaInfoAsync(
            IStorageFile file, bool ignoreDrm)
        {
            using (var stream = await file.OpenReadAsync())
            {
                IMediaInfo info   = null;
                int        result = -1;
                // Workaround for mojibake in id3v2 tags: use system code page.
                if (string.Compare(file.FileType, ".mp3", true) == 0)
                {
                    if (file is StorageFile)
                    {
                        var props = await((StorageFile)file).Properties.GetMusicPropertiesAsync();
                        var fInfo = MusicPropertiesMediaInfo.Create(props);
                        result              = NativeMethods.GetMediaInfoFromStream(stream, out IMediaInfo extraInfo);
                        fInfo.TrackNumber   = extraInfo.TrackNumber;
                        fInfo.TotalTracks   = extraInfo.TotalTracks;
                        fInfo.DiscNumber    = extraInfo.DiscNumber;
                        fInfo.TotalDiscs    = extraInfo.TotalDiscs;
                        fInfo.Date          = extraInfo.Date;
                        fInfo.Genre         = extraInfo.Genre;
                        fInfo.AllProperties = extraInfo.AllProperties;
                        info = fInfo;
                    }
                    else
                    {
                        result =
                            NativeMethods.GetMediaInfoFromStream(stream, out info);
                    }
                }
                else
                {
                    result = NativeMethods.GetMediaInfoFromStream(
                        stream,
                        out info);
                }
                if (result == 0 && info != null)
                {
                    if (ignoreDrm && !string.IsNullOrWhiteSpace(info.AllProperties["encryption"]))
                    {
                        // Throw DRM exception for upstream reference
                        throw new DrmProtectedException();
                    }

                    var prop = await file.GetBasicPropertiesAsync();

                    return(file.Path, info, prop.DateModified);
                }
                return(default((string, IMediaInfo, DateTimeOffset)));
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Reads the contents of the specified file and returns a byte array.
        /// </summary>
        /// <param name="file">The file to read.</param>
        /// <returns>When this method completes, it returns an array of bytes that represents the contents of the file.</returns>
        public static async Task <byte[]> ReadBytesAsync(this IStorageFile file)
        {
            using (var stream = await file.OpenReadAsync())
            {
#if WINDOWS_UWP
                var buffer = new byte[stream.Size];
                await stream.ReadAsync(buffer.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);

                return(buffer);
#else
                return(await stream.ToBytesAsync());
#endif
            }
        }
Exemplo n.º 22
0
        private async static Task <byte[]> ReadStorageFileToByteBuffer(IStorageFile storageFile)
        {
            IRandomAccessStream accessStream = await storageFile.OpenReadAsync();

            byte[] content = null;

            using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
            {
                content = new byte[stream.Length];
                await stream.ReadAsync(content, 0, (int)stream.Length);
            }

            return(content);
        }
Exemplo n.º 23
0
        private static async Task <object> ReadJsonFileAsync(this IStorageFile file, Type objectType)
        {
            using (var fileStream = await file.OpenReadAsync())
            {
                if (fileStream.Size == 0)
                {
                    return(null);
                }

                var serializer = JsonSerializer.Create(serialisationSettings);
                using (var reader = new StreamReader(fileStream.AsStreamForRead()))
                    using (var jsonReader = new JsonTextReader(reader))
                        return(serializer.Deserialize(jsonReader, objectType));
            }
        }
Exemplo n.º 24
0
        private async void GetFileLrc()

        {
            //var u = new Uri("ms-appdata:///MusicLrc" + musicLrc[0]);
            IStorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            IStorageFile   storageFile   = await storageFolder.GetFileAsync("5.lrc");

            // var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/5.lrc"));
            IRandomAccessStream accessStream = await storageFile.OpenReadAsync();

            using (StreamReader streamReader = new StreamReader(accessStream.AsStreamForRead((int)accessStream.Size)))
            {
                music_Lrc.Text = streamReader.ReadToEnd();
            }
        }
Exemplo n.º 25
0
        public static async Task GotPictureFromIde(IStorageFile file)
        {
            BitmapImage bitmapImage = new BitmapImage();

            using (IRandomAccessStream fileStream = await file.OpenReadAsync())
            {
                await bitmapImage.SetSourceAsync(fileStream);
            }

            WriteableBitmap writableBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);

            using (IRandomAccessStream fileStream = await file.OpenReadAsync())
            {
                await writableBitmap.SetSourceAsync(fileStream);
            }

            // TODO: edit "writableBitmap" and send it back to
            // TODO: the IDE by using the following line
            await SendPictureToIde(writableBitmap);

            // TODO: Maybe call the following line to exit the
            // TODO: Paint app after the file was sent back to the IDE
            // Application.Current.Exit();
        }
Exemplo n.º 26
0
        public static async Task <ImageFile> FileToImageFileAsync(IStorageFile storageFile, bool readStream = true)
        {
            Stream imageStream = null;

            if (readStream)
            {
                IRandomAccessStreamWithContentType RandomAccessStream = await storageFile?.OpenReadAsync();

                imageStream = RandomAccessStream?.AsStreamForWrite();
            }
            ImageProperties imageProp;
            int             width    = 0;
            int             height   = 0;
            string          filepath = String.Empty;

            if (storageFile is StorageFile sFile)
            {
                if (sFile.Properties != null)
                {
                    imageProp = await sFile.Properties.GetImagePropertiesAsync();

                    width  = (int)imageProp.Width;
                    height = (int)imageProp.Height;
                }
                //path can be empty if from the file picker dialog
                //a image path from the internet was enterted
                if (String.IsNullOrEmpty(storageFile.Path))
                {
                    filepath = sFile.FolderRelativeId;
                }
                else
                {
                    filepath = storageFile.Path;
                }
            }

            if (String.IsNullOrEmpty(filepath))
            {
                filepath = storageFile.Path;
            }

            FileInfo  fileInfo  = String.IsNullOrEmpty(filepath) ? null : new FileInfo(filepath);
            ImageFile imageFile = new ImageFile(filepath, imageStream, width, height, fileInfo);

            imageFile.Tag        = storageFile;
            imageFile.IsReadOnly = (Windows.Storage.FileAttributes.ReadOnly & storageFile.Attributes) == Windows.Storage.FileAttributes.ReadOnly;
            return(imageFile);
        }
Exemplo n.º 27
0
        public async Task LoadImageAsync()
        {
            using (var stream = await file.OpenReadAsync())
            {
                WriteableBitmap bitmap = new WriteableBitmap(width, height);
                await bitmap.SetSourceAsync(stream);

                using (var buffer = bitmap.PixelBuffer.AsStream())
                {
                    pixels = new Byte[4 * width * height];
                    buffer.Read(pixels, 0, pixels.Length);
                }

                this.bitmap = bitmap;
            }
        }
Exemplo n.º 28
0
        public async Task <IRandomAccessStream> TryGetStream(ITile tile)
        {
            StorageFolder folder = await OpenFolder(tile).ConfigureAwait(false);

            string       filename    = string.Format(CultureInfo.InvariantCulture, "{0}.tile", tile.CacheKey);
            IStorageFile storageFile = await folder.TryGetItemAsync(filename).AsTask().ConfigureAwait(false) as IStorageFile;

            if (storageFile == null)
            {
                return(null);
            }

            IRandomAccessStreamWithContentType stream = await storageFile.OpenReadAsync().AsTask().ConfigureAwait(false);

            return(stream);
        }
Exemplo n.º 29
0
        internal async static Task <string> ReadTextAsync(IStorageFile storageFile)
        {
            string text;

            IRandomAccessStream accessStream = await storageFile.OpenReadAsync();

            using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
            {
                byte[] content = new byte[stream.Length];
                await stream.ReadAsync(content, 0, (int)stream.Length);

                text = Encoding.UTF8.GetString(content, 0, content.Length);
            }

            return(text);
        }
Exemplo n.º 30
0
    internal async static Task<string> ReadTextAsync(IStorageFile storageFile)
    {
      string text;

      IRandomAccessStream accessStream = await storageFile.OpenReadAsync();

      using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
      {
        byte[] content = new byte[stream.Length];
        await stream.ReadAsync(content, 0, (int)stream.Length);

        text = Encoding.UTF8.GetString(content, 0, content.Length);
      }

      return text;
    }
Exemplo n.º 31
0
        public async Task <string> ReadTextAsync(string filename)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            IStorageFile  storageFile = await localFolder.GetFileAsync(filename);

            using (IRandomAccessStream stream = await storageFile.OpenReadAsync())
            {
                using (DataReader dataReader = new DataReader(stream))
                {
                    uint length = (uint)stream.Size;
                    await dataReader.LoadAsync(length);

                    return(dataReader.ReadString(length));
                }
            }
        }
Exemplo n.º 32
0
        public static async Task <string> ReadAllTextAsync(this IStorageFile file)
        {
            // Read the whole file as a string.
            string contents = null;

            using (IRandomAccessStream textStream = await file.OpenReadAsync())
            {
                using (DataReader textReader = new DataReader(textStream))
                {
                    uint textLength = (uint)textStream.Size;
                    await textReader.LoadAsync(textLength);

                    contents = textReader.ReadString(textLength);
                }
            }
            return(contents);
        }
        private async Task GetFileStream()
        {
            IStorageFile   file       = null;
            FileOpenPicker filePicker = new FileOpenPicker();

            filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
            filePicker.FileTypeFilter.Add(".pcm");
            filePicker.ViewMode = PickerViewMode.Thumbnail;
            file = await filePicker.PickSingleFileAsync();

            // File can be null if cancel is hit in the file picker
            if (file == null)
            {
                return;
            }
            var ras = await file.OpenReadAsync();

            fileStream = ras.AsStreamForRead();
        }
Exemplo n.º 34
0
        public void Load(string filename)
        {
#if !WINDOWS_PHONE // iOS and Android
            string docsPath = Environment.GetFolderPath(
                Environment.SpecialFolder.Personal);
            string filepath = Path.Combine(docsPath, filename);
            string text     = File.ReadAllText(filepath);

            // Break string into Title and Text.
            int index = text.IndexOf('\n');
            this.Title = text.Substring(0, index);
            this.Text  = text.Substring(index + 1);
#else // Windows Phone
            StorageFolder localFolder =
                ApplicationData.Current.LocalFolder;
            IAsyncOperation <StorageFile> createOp =
                localFolder.GetFileAsync(filename);
            createOp.Completed = (asyncInfo1, asyncStatus1) =>
            {
                IStorageFile storageFile = asyncInfo1.GetResults();
                IAsyncOperation <IRandomAccessStreamWithContentType>
                openOp = storageFile.OpenReadAsync();
                openOp.Completed = (asyncInfo2, asyncStatus2) =>
                {
                    IRandomAccessStream stream     = asyncInfo2.GetResults();
                    DataReader          dataReader = new DataReader(stream);
                    uint length = (uint)stream.Size;
                    DataReaderLoadOperation loadOp =
                        dataReader.LoadAsync(length);
                    loadOp.Completed = (asyncInfo3, asyncStatus3) =>
                    {
                        string text = dataReader.ReadString(length);
                        dataReader.Dispose();

                        // Break string into Title and Text.
                        int index = text.IndexOf('\n');
                        this.Title = text.Substring(0, index);
                        this.Text  = text.Substring(index + 1);
                    };
                };
            };
#endif
        }
Exemplo n.º 35
0
        internal static async Task ResizeAndSaveAs(IStorageFile source, IStorageFile destination, 
            int targetDimension)
        {
            // open the file...
            using(var sourceStream = await source.OpenReadAsync())
            {
                // step one, get a decoder...
                var decoder = await BitmapDecoder.CreateAsync(sourceStream);

                // step two, create somewhere to put it...
                using(var destinationStream = await destination.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // step three, create an encoder...
                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(destinationStream, decoder);

                    // how big is it?
                    uint width = decoder.PixelWidth;
                    uint height = decoder.PixelHeight;
                    decimal ratio = (decimal)width / (decimal)height;

                    // orientation?
                    bool portrait = width < height;

                    // step four, configure it...
                    if (portrait)
                    {
                        encoder.BitmapTransform.ScaledHeight = (uint)targetDimension;
                        encoder.BitmapTransform.ScaledWidth = (uint)((decimal)targetDimension * ratio);
                    }
                    else
                    {
                        encoder.BitmapTransform.ScaledWidth = (uint)targetDimension;
                        encoder.BitmapTransform.ScaledHeight = (uint)((decimal)targetDimension / ratio);
                    }

                    // step five, write it...
                    await encoder.FlushAsync();
                }
            }
        }
Exemplo n.º 36
0
        public async Task AddKeyFile(IStorageFile file)
        {
            KeyfileName = file.Name;
            using (var input = await file.OpenReadAsync())
                await _password.AddKeyFile(input);

            NotifyOfPropertyChange(() => CanOpenDatabase);
            NotifyOfPropertyChange(() => CanClearKeyfile);
            NotifyOfPropertyChange(() => KeyfileGroupVisibility);
        }
Exemplo n.º 37
0
		//http://www.techcoil.com/blog/sending-a-file-and-some-form-data-via-http-post-in-c/
		public static async Task<WebResult> POST(string url, IStorageFile file, Dictionary<string, string> additionalContent, string token = null)
		{
			string boundaryString = "----DiscordUWP8Boundary" + new Random().Next(0, 999);

			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			request.Method = "POST";
			request.ContentType = "multipart/form-data; boundary=" + boundaryString;

			request.Headers["Connection"] = "Keep-Alive";
			if (token != null) request.Headers["Authorization"] = token;

			MemoryStream postDataStream = new MemoryStream();
			StreamWriter postDataWriter = new StreamWriter(postDataStream);

			foreach(KeyValuePair<string, string> content in additionalContent)
			{
				postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
				postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}", content.Key, content.Value);
			}

			postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
			postDataWriter.Write("Content-Disposition: form-data;" + "name=\"{0}\";" + "filename=\"{1}\"" + "\r\nContent-Type: {2}\r\n\r\n", "file", Path.GetFileName(file.Path), Path.GetExtension(file.Path));
			postDataWriter.Flush();

			// Read the file

			var stream = await file.OpenReadAsync();

			byte[] buffer = new byte[1024];

			using (var ss = stream.AsStreamForRead(1024))
			{
				int bytesRead = 0;
				while ((bytesRead = await ss.ReadAsync(buffer, 0, buffer.Length)) != 0)
				{
					postDataStream.Write(buffer, 0, bytesRead);
				}
			}

			postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
			postDataWriter.Flush();

			// Dump the post data from the memory stream to the request stream
			using (Stream s = await request.GetRequestStreamAsync())
			{
				postDataStream.WriteTo(s);
			}

			postDataWriter.Dispose();
			postDataStream.Dispose();

			try
			{
				using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
				{
					using (StreamReader reader = new StreamReader(CheckForCompression(response), Encoding.UTF8))
					{
						return new WebResult { Data = reader.ReadToEnd(), Status = response.StatusCode };
					}
				}
			}
			catch (WebException e)
			{
				using (HttpWebResponse response = (HttpWebResponse)e.Response)
				{
					using (StreamReader reader = new StreamReader(CheckForCompression(response), Encoding.UTF8))
					{
						return new WebResult { Data = reader.ReadToEnd(), Status = response.StatusCode };
					}
				}
			}
		}
Exemplo n.º 38
0
        private static async Task<ZipArchiveEntry> DoCreateEntryFromFile(ZipArchive destination, IStorageFile sourceFile, string entryName, CompressionLevel? compressionLevel)
        {
            if (destination == null)
                throw new ArgumentNullException("destination");
            if (sourceFile == null)
                throw new ArgumentNullException("sourceFile");
            if (entryName == null)
                throw new ArgumentNullException("entryName");
            using (Stream stream = (await sourceFile.OpenReadAsync()).AsStream())
            {
                ZipArchiveEntry zipArchiveEntry = compressionLevel.HasValue ? destination.CreateEntry(entryName, compressionLevel.Value) : destination.CreateEntry(entryName);

                var props = await sourceFile.GetBasicPropertiesAsync();

                DateTime dateTime = props.DateModified.UtcDateTime;
                if (dateTime.Year < 1980 || dateTime.Year > 2107)
                    dateTime = new DateTime(1980, 1, 1, 0, 0, 0);
                zipArchiveEntry.LastWriteTime = (DateTimeOffset)dateTime;
                using (Stream destination1 = zipArchiveEntry.Open())
                {
                    await stream.CopyToAsync(destination1);
                }
                return zipArchiveEntry;
            }
        }