/// <summary> /// This is the click handler for the 'Copy Strings' button. Here we will parse the /// strings contained in the ElementsToWrite text block, write them to a stream using /// DataWriter, retrieve them using DataReader, and output the results in the /// ElementsRead text block. /// </summary> /// <param name="sender">Contains information about the button that fired the event.</param> /// <param name="e">Contains state information and event data associated with a routed event.</param> private async void TransferData(object sender, RoutedEventArgs e) { // Initialize the in-memory stream where data will be stored. using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { // Create the data writer object backed by the in-memory stream. using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream)) { dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Write each element separately. foreach (string inputElement in inputElements) { uint inputElementSize = dataWriter.MeasureString(inputElement); dataWriter.WriteUInt32(inputElementSize); dataWriter.WriteString(inputElement); } // Send the contents of the writer to the backing stream. await dataWriter.StoreAsync(); // For the in-memory stream implementation we are using, the flushAsync call is superfluous, // but other types of streams may require it. await dataWriter.FlushAsync(); // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing // its subsequent use by the DataReader below. dataWriter.DetachStream(); } // Create the input stream at position 0 so that the stream can be read from the beginning. stream.Seek(0); using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { // The encoding and byte order need to match the settings of the writer we previously used. dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Once we have written the contents successfully we load the stream. await dataReader.LoadAsync((uint)stream.Size); var receivedStrings = ""; // Keep reading until we consume the complete stream. while (dataReader.UnconsumedBufferLength > 0) { // Note that the call to readString requires a length of "code units" to read. This // is the reason each string is preceded by its length when "on the wire". uint bytesToRead = dataReader.ReadUInt32(); receivedStrings += dataReader.ReadString(bytesToRead) + "\n"; } // Populate the ElementsRead text block with the items we read from the stream. ElementsRead.Text = receivedStrings; } } }
// Read out and print the message received from the socket. private async void StartReader(Windows.Networking.Proximity.ProximityStreamSocket socket, Windows.Storage.Streams.DataReader reader) { uint initialLength = 4; try { await reader.LoadAsync(initialLength); uint msgLength = (uint)reader.ReadInt32(); try { await reader.LoadAsync(msgLength); string message = reader.ReadString(msgLength); WriteMessageText("Received message: " + message + "\n"); // After receiving a message, listen for the next message. StartReader(socket, reader); } catch (Exception e) { WriteMessageText("Error: " + e.Message + "\n"); socket.Dispose(); } } catch (Exception e) { WriteMessageText("Error: " + e.Message + "\n"); socket.Dispose(); } }
public static async System.Threading.Tasks.Task <byte[]> ReadBytesFromFileAsync(string fileName) { try { Windows.Storage.StorageFolder tempFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(Options.options.tempFolderPath); Windows.Storage.StorageFile file = await tempFolder.GetFileAsyncServiceAsync(text, apiArgs); // TODO: obsolete to use DataReader? use await Windows.Storage.FileIO.Read...(file); using (Windows.Storage.Streams.IRandomAccessStream stream = await file.OpenReadAsync()) { using (Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0))) { await reader.LoadAsync((uint)stream.Size); byte[] bytes = new byte[stream.Size]; reader.ReadBytes(bytes); return(bytes); } } } catch (Exception ex) { Log.WriteLine(ex.Message); return(null); } }
public async void LoadCustomersFromFile() { try { StorageFolder storageFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await storageFolder.GetFileAsync("CustomerSaveFile.sav"); string text; var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); text = dataReader.ReadString(numBytesLoaded); } } text = text.Replace("\n", string.Empty); string[] words = text.Split('%'); for (int i = 0; i < words.Length - 1; i += 3) { Customer tempCustomer = new Customer(words[i], words[i + 1], words[i + 2]); CustomerCollection.Add(tempCustomer); } } catch (System.IO.FileNotFoundException e) { errorMessage += $"{e.Message}\n"; } }
public static async System.Threading.Tasks.Task LoadPhotoTask(string size, string name) { Windows.Storage.StorageFolder installationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; Windows.Storage.StorageFolder assetsFolder = await installationFolder.GetFolderAsync("Assets"); Windows.Storage.StorageFolder imagesFolder = await assetsFolder.GetFolderAsync("Images"); Windows.Storage.StorageFolder sizeFolder = null; if (size.Equals("0.3MP")) { sizeFolder = await imagesFolder.GetFolderAsync("0_3mp"); } else { sizeFolder = await imagesFolder.GetFolderAsync(size.ToLower()); } IReadOnlyList<Windows.Storage.StorageFile> files = await sizeFolder.GetFilesAsync(); foreach (var file in files) { if (name.Equals(file.Name)) { using (Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenReadAsync()) { ImageJpg = new byte[fileStream.Size]; using (var reader = new Windows.Storage.Streams.DataReader(await file.OpenReadAsync())) { await reader.LoadAsync((uint)fileStream.Size); reader.ReadBytes(ImageJpg); } } break; } } }
public async void LoadCustomerOrdersFromFile(string SaveFileName, ObservableCollection <CustomerOrder> customerOrders) { try { StorageFolder storageFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await storageFolder.GetFileAsync(SaveFileName); string text; var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); text = dataReader.ReadString(numBytesLoaded); } } text = text.Replace("\n", string.Empty); string[] words = text.Split(new char[] { '%', '¤' }); for (int i = 0; i < words.Length - 1; i += 10) { CustomerOrder tempOrder = new CustomerOrder(new Customer(words[i + 1], words[i + 2], words[i + 3]), new Merchandise(words[i + 5], words[i + 6], Int32.Parse(words[i + 7])), Int32.Parse(words[i + 9])); tempOrder.OrderDateTime = DateTime.Parse(words[i]); customerOrders.Add(tempOrder); } } catch (System.IO.FileNotFoundException e) { errorMessage += $"{e.Message}\n"; } }
private async void OpenFileButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker { ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail, SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary }; picker.FileTypeFilter.Add(".yo"); SourceFile = await picker.PickSingleFileAsync(); if (SourceFile == null) { return; } var stream = await SourceFile.OpenAsync(FileAccessMode.Read); ulong size = stream.Size; SourceList.Clear(); using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); SourceText = dataReader.ReadString(numBytesLoaded); RealSource = SourceText.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); } this.SourceListView.SelectedIndex = 0; WorkCompletedForSource(); LoadInstructions(); }
private async void C_BUTTON_LOAD_ENTITY_Click(object sender,RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeFilter.Add(".json"); // Default file name if the user does not type one in or select a file to replace var t_storagefile = await picker.PickSingleFileAsync(); if (t_storagefile == null) { return; } String json_str; using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(transaction.Stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)transaction.Stream.Size); json_str = dataReader.ReadString(numBytesLoaded); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } Deserialize(json_str); }
//We use a protected override void to execute code as soon as the page is loaded into memory protected async override void OnNavigatedTo(NavigationEventArgs e) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile signInInfo = await storageFolder.CreateFileAsync("signin.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); var stream = await signInInfo.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string signinAddress = dataReader.ReadString(numBytesLoaded); //string currentUser = emailBox.Text; if (signinAddress.ToString() == "") { emailBox.Text = "@wh-at.net"; } else { emailBox.Text = signinAddress.ToString(); Frame.Navigate(typeof(helpdesk)); } } } stream.Dispose(); }
public static async System.Threading.Tasks.Task LoadFilterTask(string name) { var installationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; var assetsFolder = await installationFolder.GetFolderAsync("Assets"); var filtersFolder = await assetsFolder.GetFolderAsync("Filters"); string filename = null; if (name.Equals("Red Ton")) { filename = "map1.png"; } var file = await filtersFolder.GetFileAsync(filename); using (var fileStream = await file.OpenReadAsync()) { FilterJpg = new byte[fileStream.Size]; using (var reader = new Windows.Storage.Streams.DataReader(await file.OpenReadAsync())) { await reader.LoadAsync((uint)fileStream.Size); reader.ReadBytes(FilterJpg); } } }
public static async Task <string> ReadFile(string filename, string folderPath = "DataCache", bool isInstallationFolder = false) { StorageFolder localFolder; if (isInstallationFolder) { localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; } else { localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; } var folder = await localFolder.GetFolderAsync(folderPath); //var folder = await installFolder.GetFolderAsync("Assets/Constellation"); var file = await folder.GetFileAsync(filename); var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var inStream = fs.GetInputStreamAt(0); Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inStream); await reader.LoadAsync((uint)fs.Size); string data = reader.ReadString((uint)fs.Size); reader.DetachStream(); return(data); }
private void buttonLoadBinaryData_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".bin"); var dispatcher = this.Dispatcher; ((Action)(async() => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async() => { var file = await picker.PickSingleFileAsync(); if (file == null) { return; } var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var reader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); var count = await reader.LoadAsync((uint)stream.Size); var buffer = reader.ReadBuffer(count); var str = Util.BinaryBufferToBinaryString(buffer); var index = (sender as Windows.UI.Xaml.Controls.Control).Name.Replace("buttonLoadBinaryData", ""); TextBox textBox = Util.FindControl(Input, "textBoxBinaryData" + index) as TextBox; await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => { textBox.Text = str; textBox.SetValue(RawBinaryDataProperty, buffer); })); })); } )).Invoke(); }
private async void Read_text_file_stream_Click(object sender, RoutedEventArgs e) { // Get the sample file Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt"); // Open stream to sample file var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read); // Get size of the stream for user later ulong size = stream.Size; // Get the input stream using (var inputStream = stream.GetInputStreamAt(0)) { // Read the stream using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string text = dataReader.ReadString(numBytesLoaded); // Show contents of file this.Read_File_Contents_Stream.Text = text; } } }
public static async Task <Encoding> GetDbcsEncoding(string name) { try { return(GetEncoding(name)); } catch { //not supported by system } name = name.ToLower(); var encoding = new DbcsEncoding { _webName = name }; if (Cache.ContainsKey(name)) { var tuple = Cache[name]; encoding._dbcsToUnicode = tuple.Item1; encoding._unicodeToDbcs = tuple.Item2; return(encoding); } var dbcsToUnicode = new char[0x10000]; var unicodeToDbcs = new ushort[0x10000]; try { var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync( new Uri(string.Format("ms-appx:///EncodingMaps/{0}.bin", name))); using (var fs = await file.OpenReadAsync()) using (var reader = new Windows.Storage.Streams.DataReader(fs)) { await reader.LoadAsync((uint)fs.Size); for (int i = 0; i < 0xffff; i++) { ushort u = reader.ReadUInt16(); unicodeToDbcs[i] = u; } for (int i = 0; i < 0xffff; i++) { ushort u = reader.ReadUInt16(); dbcsToUnicode[i] = (char)u; } } Cache[name] = new Tuple <char[], ushort[]>(dbcsToUnicode, unicodeToDbcs); encoding._dbcsToUnicode = dbcsToUnicode; encoding._unicodeToDbcs = unicodeToDbcs; return(encoding); } catch { return(null); } }
/// <summary> /// Creates and adds a time track objects into the Items collection. /// </summary> public async void LoadData() { var fileList = await ApplicationData.Current.LocalFolder.GetFilesAsync(); var file = fileList.FirstOrDefault(f => f.Name == localFileName); if (file != null) { using (var stream = await file.OpenReadAsync()) { using (var dr = new Windows.Storage.Streams.DataReader(stream)) { try { await dr.LoadAsync(unchecked((uint)stream.Size)); var numberOfItems = dr.ReadInt32(); ObservableCollection<TrackItem> loadingItems = new ObservableCollection<TrackItem>(); for (int x = 0; x < numberOfItems; x++) { TrackItem item = new TrackItem(); item.Start = dr.ReadDateTime(); item.End = dr.ReadDateTime(); int topicLength = dr.ReadInt32(); item.Topic = dr.ReadString((uint)topicLength); loadingItems.Add(item); } bool currentItemExists = dr.ReadBoolean(); TrackItem loadingCurrentItem = null; if (currentItemExists) { loadingCurrentItem = new TrackItem(); loadingCurrentItem.Start = dr.ReadDateTime(); int topicLength = dr.ReadInt32(); loadingCurrentItem.Topic = dr.ReadString((uint)topicLength); } dr.DetachStream(); Items = loadingItems; OnPropertyChanged(nameof(Items)); CurrentItem = loadingCurrentItem; IsDataLoaded = true; } catch { try { await file.DeleteAsync(); } catch { } CurrentItem = null; IsDataLoaded = true; } } } } else { // Sample data; replace with real data Items.Add(new TrackItem() { Topic = "First Tracked Item", Start = new DateTimeOffset(new DateTime(2015, 11, 5, 9, 0, 0), new TimeSpan(-6, 0, 0)), End = new DateTimeOffset(new DateTime(2015, 11, 5, 11, 30, 0), new TimeSpan(-6, 0, 0)), }); Items.Add(new TrackItem() { Topic = "Second Tracked Item", Start = new DateTimeOffset(new DateTime(2015, 11, 5, 12, 30, 0), new TimeSpan(-6, 0, 0)), End = new DateTimeOffset(new DateTime(2015, 11, 5, 17, 0, 0), new TimeSpan(-6, 0, 0)), }); CurrentItem = null; this.IsDataLoaded = true; } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { //Select problem button Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile problemInfo = await storageFolder.CreateFileAsync("problem.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); var problemStream = await problemInfo.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong problemSize = problemStream.Size; using (var inputStream = problemStream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)problemSize); string problemContent = dataReader.ReadString(numBytesLoaded); if (problemContent == "") { selectProblemButton.Content = "choose a problem"; } else { selectProblemButton.Content = problemContent.ToString(); } } } problemStream.Dispose(); //Select room button Windows.Storage.StorageFile roomInfo = await storageFolder.CreateFileAsync("room.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); var roomStream = await roomInfo.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong roomSize = roomStream.Size; using (var inputStream = roomStream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)roomSize); string roomContent = dataReader.ReadString(numBytesLoaded); if (roomContent == "") { selectRoomButton.Content = "choose a room"; } else { selectRoomButton.Content = roomContent.ToString(); } } } roomStream.Dispose(); }
private async Task <byte[]> GetAudioBytes(Windows.Storage.Streams.InMemoryRandomAccessStream _audioStream) { using (var dataReader = new Windows.Storage.Streams.DataReader(_audioStream.GetInputStreamAt(0))) { await dataReader.LoadAsync((uint)_audioStream.Size); byte[] buffer = new byte[(int)_audioStream.Size]; dataReader.ReadBytes(buffer); return(buffer); } }
private void I2c_I2cReplyEvent(byte address_, byte reg_, Windows.Storage.Streams.DataReader response) { byte[] data = new byte[2]; response.ReadBytes(data); //byte[] data = Encoding.UTF8.GetBytes(response); int curr = i2cReading.Dequeue(); UpdateData(curr, data[1]); System.Diagnostics.Debug.WriteLine("" + Convert.ToString(address_) + "-" + curr.ToString() + ": " + BitConverter.ToString(data)); isReading = false; }
public async Task <string> GetData(Windows.Storage.Streams.IBuffer data, uint scanDataType) { try { string result = null; if (data == null) { result = "No data"; } else { switch (Windows.Devices.PointOfService.BarcodeSymbologies.GetName(scanDataType)) { case "Ean13": case "Ean8": case "Code128": case "Qr": case "Code93": case "Code39": case "Gs1128": case "DataMatrix": case "Gs1128Coupon": case "Gs1DatabarType1": case "Gs1DatabarType2": case "Gs1DatabarType3": case "Upca": case "Upce": case "TfInd": case "TfInt": case "TfStd": case "UccEan128": case "Ean13Add2": case "Ean13Add5": Windows.Storage.Streams.DataReader reader = Windows.Storage.Streams.DataReader.FromBuffer(data); result = reader.ReadString(data.Length).ToString(); byte[] bytes = Encoding.ASCII.GetBytes(result); result = Encoding.UTF8.GetString(bytes); break; default: result = string.Format("Decoded data unavailable. Raw label data: {0}", GetData(data)); break; } } return(result); } catch (Exception ex) { //await DisplayAlert("Error", "GetData failed, Code:" + " Message:" + ex.Message, "OK"); } return(""); }
public static async Task<List<Session>> DeserializeLocalSessions(StorageFile file) { using (var stream = await file.OpenSequentialReadAsync()) { using (var dr = new Windows.Storage.Streams.DataReader(stream)) { var numberOfSessions = dr.ReadInt32(); List<Session> rv = new List<Session>(numberOfSessions); for (int x = 0; x < numberOfSessions; x++) { rv.Add(LoadSession(dr)); } return rv; } } }
/// <summary> /// 将文件转换为字节数组 /// </summary> /// <param name="file"></param> /// <returns></returns> public static async Task <byte[]> AsByteArray(this Windows.Storage.StorageFile file) { Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0)); await reader.LoadAsync((uint)fileStream.Size); byte[] pixels = new byte[fileStream.Size]; reader.ReadBytes(pixels); return(pixels); }
// Reference socket streams for writing and reading messages. private void SendMessage(Windows.Networking.Proximity.ProximityStreamSocket socket) { // Get the network socket from the proximity connection. proximitySocket = socket; // Create DataWriter for writing messages to peers. dataWriter = new Windows.Storage.Streams.DataWriter(proximitySocket.OutputStream); // Listen for messages from peers. Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(proximitySocket.InputStream); StartReader(proximitySocket, dataReader); }
private async Task <string> IncludeLastScript(Stream input) { var inputStream = input.AsInputStream(); string result; using (var dataReader = new Windows.Storage.Streams.DataReader(input.AsInputStream())) { uint numBytesLoaded = await dataReader.LoadAsync((uint)input.Length); string text = dataReader.ReadString(numBytesLoaded); result = text.Replace(@"<!-- INCLUDE xml for last-script -->", mostRecentBlocks); } return(result); }
public async void LoadPresets() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeFilter.Add(".json"); // Default file name if the user does not type one in or select a file to replace var t_storagefile = await picker.PickSingleFileAsync(); if (t_storagefile == null) { return; } String json_str; using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(transaction.Stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)transaction.Stream.Size); json_str = dataReader.ReadString(numBytesLoaded); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } List <PresetItem> list = null; try { list = (List <PresetItem>)Serial.JsonHelper.FromJson(json_str, m_Presets.GetType()); }catch (Exception e) { return; } if (list == null) { return; } C_PRESETLIST.ItemsSource = null; foreach (PresetItem item in list) { m_Presets.Add(item); } C_PRESETLIST.ItemsSource = m_Presets; }
public void Chat() { var DataReader = new Windows.Storage.Streams.DataReader(client.InputStream); byte[] getByte = new byte[5000]; DataReader.ReadBytes(getByte); Encoding code = Encoding.GetEncoding("UTF-8"); string RemoteData = code.GetString(getByte, 0, getByte.Length); Messages.Add(new Message("Your Friend", DateTime.Now, RemoteData, false)); var DataWriter = new Windows.Storage.Streams.DataWriter(client.OutputStream); DataWriter.WriteString("test\n"); Messages.Add(new Message("You", DateTime.Now, textBox.Text, true)); }
public static async System.Threading.Tasks.Task <int> SynSpeechWriteToFileAsync(string text, string fileName) { using (Windows.Media.SpeechSynthesis.SpeechSynthesizer synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer()) { try { using (Windows.Media.SpeechSynthesis.SpeechSynthesisStream synthStream = await synth.SynthesizeTextToStreamAsyncServiceAsync(text, apiArgs)) // doesn't handle special characters such as quotes { // TODO: obsolete to use DataReader? use await Windows.Storage.FileIO.Read...(file); using (Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(synthStream)) { await reader.LoadAsync((uint)synthStream.Size); Windows.Storage.Streams.IBuffer buffer = reader.ReadBuffer((uint)synthStream.Size); Windows.Storage.StorageFolder tempFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(Options.options.tempFolderPath); Windows.Storage.StorageFile srcFile = await tempFolder.CreateFileAsync(Options.options.audio.speechSynthesisFileName, Windows.Storage.CreationCollisionOption.ReplaceExisting); await Windows.Storage.FileIO.WriteBufferAsync(srcFile, buffer); Windows.Storage.FileProperties.MusicProperties musicProperties = await srcFile.Properties.GetMusicPropertiesAsync(); Log.WriteLine("Bitrate:" + musicProperties.Bitrate); Windows.Media.MediaProperties.MediaEncodingProfile profile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateWav(Windows.Media.MediaProperties.AudioEncodingQuality.Low); Windows.Media.Transcoding.MediaTranscoder transcoder = new Windows.Media.Transcoding.MediaTranscoder(); Windows.Storage.StorageFile destFile = await tempFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting); Windows.Media.Transcoding.PrepareTranscodeResult result = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile); if (result.CanTranscode) { await result.TranscodeAsync(); } else { Log.WriteLine("can't transcode file:" + result.FailureReason.ToString()); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } return(0); }
private async void OnConnection(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args) { Debug.LogError("New client" + sender.Information.LocalPort); var reader = new Windows.Storage.Streams.DataReader(args.Socket.InputStream); try { while (true) { // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the string. uint stringLength = reader.ReadUInt32(); uint actualStringLength = await reader.LoadAsync(stringLength); if (stringLength != actualStringLength) { // The underlying socket was closed before we were able to read the whole data. return; } // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal // the text back to the UI thread. //NotifyUserFromAsyncThread( // String.Format("Received data: \"{0}\"", reader.ReadString(actualStringLength)), // NotifyType.StatusMessage); } } catch (Exception ex) { Debug.LogException(ex); // If this is an unknown status it means that the error is fatal and retry will likely fail. if (Windows.Networking.Sockets.SocketError.GetStatus(ex.HResult) == Windows.Networking.Sockets.SocketErrorStatus.Unknown) { throw; } } }
private async void LoadRolodexButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; picker.FileTypeFilter.Add(".txt"); picker.FileTypeFilter.Add(".csv"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string text = dataReader.ReadString(numBytesLoaded); var lines = text.Split('\n'); foreach (var line in lines) { var components = line.Split(','); if (components.Length == 6) { var newCoord = new Coordinates(components[0], components[1], components[2], float.Parse(components[3]), float.Parse(components[4]), float.Parse(components[5])); Collection.Add(newCoord); } } } } appendLineToConsole("Loaded File: " + file.Name); } else { appendLineToConsole("Operation Cancelled"); } }
async Task <byte[]> StorageFileToByteArray(Windows.Storage.StorageFile file) { byte[] fileBytes = null; using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { fileBytes = new byte[stream.Size]; using (var reader = new Windows.Storage.Streams.DataReader(stream)) { await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(fileBytes); } } return(fileBytes); }
public async Task <bool> ConnectAsync() { try { sock = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName hostname = new Windows.Networking.HostName(ServerName); await sock.ConnectAsync(hostname, ServiceName); writer = new Windows.Storage.Streams.DataWriter(sock.OutputStream); reader = new Windows.Storage.Streams.DataReader(sock.InputStream); StartReceiveDataAsync(); return(true); } catch { return(false); } }
public static async Task <string> ReadFile(string filename) { var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; var folder = localFolder; var file = await folder.GetFileAsync(filename); var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var inStream = fs.GetInputStreamAt(0); Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inStream); await reader.LoadAsync((uint)fs.Size); string data = reader.ReadString((uint)fs.Size); reader.DetachStream(); return(data); }
/// <summary> /// reads the data from the specified file with the offset as the starting point the size /// and writes them to a byte[] buffer /// </summary> /// <param name="fullPath"></param> /// <returns></returns> public async Task <byte[]> Restore(string fullPath, ulong offset, ulong size) { byte[] dataArray = null; try { Windows.Storage.StorageFile file = await applicationData.LocalFolder.GetFileAsync(fullPath); if (file != null) { if (size <= 0) { var prop = await file.GetBasicPropertiesAsync(); if (prop != null) { size = prop.Size; } } var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); if (stream != null) { using (var inputStream = stream.GetInputStreamAt(offset)) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); dataArray = new byte[numBytesLoaded]; if (dataArray != null) { dataReader.ReadBytes(dataArray); } } } } } } catch (Exception) { } return(dataArray); }
private async Task <string> ReadFile(StorageFile file) { var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); string textBody; ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; uint numBytesLoaded = await dataReader.LoadAsync((uint)size); textBody = dataReader.ReadString(numBytesLoaded); } } return(textBody); }
public async Task<string> readFile() { string text; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile dataFile = await storageFolder.GetFileAsync("db.txt"); var stream = await dataFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); text = dataReader.ReadString(numBytesLoaded); dataReader.Dispose(); } } stream.Dispose(); return text; }
public byte[] LoadBinary(string path) { var result = Task.Run(async () => { var folder = Windows.Storage.ApplicationData.Current.LocalCacheFolder; Windows.Storage.StorageFile file = await folder.GetFileAsync(path); byte[] fileBytes = null; using (var stream = await file.OpenReadAsync()) { fileBytes = new byte[stream.Size]; using (var reader = new Windows.Storage.Streams.DataReader(stream)) { await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(fileBytes); } } return fileBytes; } ); result.Wait(); return result.Result; }
private void buttonLoadBinaryData_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".bin"); var dispatcher = this.Dispatcher; ((Action)(async () => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () => { var file = await picker.PickSingleFileAsync(); if (file == null) { return; } var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var reader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); var count = await reader.LoadAsync((uint)stream.Size); var buffer = reader.ReadBuffer(count); var str = Util.BinaryBufferToBinaryString(buffer); var index = (sender as Windows.UI.Xaml.Controls.Control).Name.Replace("buttonLoadBinaryData", ""); TextBox textBox = Util.FindControl(Input, "textBoxBinaryData" + index) as TextBox; await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => { textBox.Text = str; textBox.SetValue(RawBinaryDataProperty, buffer); })); })); } )).Invoke(); }
/// <summary> /// reads the data from the specified file with the offset as the starting point the size /// and writes them to a byte[] buffer /// </summary> /// <param name="fullPath"></param> /// <returns></returns> public async Task<byte[]> Restore(string fullPath, ulong offset, ulong size) { byte[] dataArray = null; try { Windows.Storage.StorageFile file = await applicationData.LocalFolder.GetFileAsync(fullPath); if(file!=null) { if (size <= 0) { var prop = await file.GetBasicPropertiesAsync(); if(prop!= null) size = prop.Size; } var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); if (stream != null) { using (var inputStream = stream.GetInputStreamAt(offset)) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); dataArray = new byte[numBytesLoaded]; if (dataArray != null) { dataReader.ReadBytes(dataArray); } } } } } } catch (Exception ) { } return dataArray; }
/// <summary> /// This is the click handler for the 'Hex Dump' button. Open the image file we want to /// perform a hex dump on. Then open a sequential-access stream over the file and use /// ReadBytes() to extract the binary data. Finally, convert each byte to hexadecimal, and /// display the formatted output in the HexDump textblock. /// </summary> /// <param name="sender">Contains information about the button that fired the event.</param> /// <param name="e">Contains state information and event data associated with a routed event.</param> private async void HexDump(object sender, RoutedEventArgs e) { try { // Retrieve the uri of the image and use that to load the file. Uri uri = new Uri("ms-appx:///assets/Strawberry.png"); var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); // Open a sequential-access stream over the image file. using (var inputStream = await file.OpenSequentialReadAsync()) { // Pass the input stream to the DataReader. using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint currChunk = 0; uint numBytes; ReadBytesOutput.Text = ""; // Create a byte array which can hold enough bytes to populate a row of the hex dump. var bytes = new byte[bytesPerRow]; do { // Load the next chunk into the DataReader buffer. numBytes = await dataReader.LoadAsync(chunkSize); // Read and print one row at a time. var numBytesRemaining = numBytes; while (numBytesRemaining >= bytesPerRow) { // Use the DataReader and ReadBytes() to fill the byte array with one row worth of bytes. dataReader.ReadBytes(bytes); PrintRow(bytes, (numBytes - numBytesRemaining) + (currChunk * chunkSize)); numBytesRemaining -= bytesPerRow; } // If there are any bytes remaining to be read, allocate a new array that will hold // the remaining bytes read from the DataReader and print the final row. // Note: ReadBytes() fills the entire array so if the array being passed in is larger // than what's remaining in the DataReader buffer, an exception will be thrown. if (numBytesRemaining > 0) { bytes = new byte[numBytesRemaining]; // Use the DataReader and ReadBytes() to fill the byte array with the last row worth of bytes. dataReader.ReadBytes(bytes); PrintRow(bytes, (numBytes - numBytesRemaining) + (currChunk * chunkSize)); } currChunk++; // If the number of bytes read is anything but the chunk size, then we've just retrieved the last // chunk of data from the stream. Otherwise, keep loading data into the DataReader buffer. } while (numBytes == chunkSize); } } } catch (Exception ex) { ReadBytesOutput.Text = ex.Message; } }
/// <summary> /// This is an internal method called from ReadInternal method. /// </summary> /// <param name="buffer">The byte array, passed to Read method.</param> /// <param name="offset">The offset in the buffer array to begin writing.</param> /// <param name="count">The number of bytes to read.</param> /// <param name="timeout">Milliseconds before a time-out occurs.</param> /// <param name="ct">A cancellation_token will be signaled by user cancellation.</param> /// <returns> /// The result of Task contains the length of bytes read. This may be less than count. /// </returns> private Task<int> ReadPartial( Windows.Storage.Streams.IBuffer buffer, int offset, int count, int timeout, System.Threading.CancellationToken ct ) { // Buffer check. if ((int)buffer.Length < (offset + count)) { throw new ArgumentException("Capacity of buffer is not enough."); } var inputStream = this.cdcData.BulkInPipes[0].InputStream; var reader = new Windows.Storage.Streams.DataReader(inputStream); return Task.Run(async () => { // CancellationTokenSource to cancel tasks. var cancellationTokenSource = new System.Threading.CancellationTokenSource(); // LoadAsync task. var loadTask = reader.LoadAsync((uint)count).AsTask<uint>(cancellationTokenSource.Token); // A timeout task that completes after the specified delay. var timeoutTask = Task.Delay(timeout == Constants.InfiniteTimeout ? System.Threading.Timeout.Infinite : timeout, cancellationTokenSource.Token); // Cancel tasks by user's cancellation. bool canceledByUser = false; ct.Register(()=> { canceledByUser = true; cancellationTokenSource.Cancel(); }); // Wait tasks. Task[] tasks = { loadTask, timeoutTask }; var signaledTask = await Task.WhenAny(tasks); // Check the task status. bool loadCompleted = signaledTask.Equals(loadTask) && loadTask.IsCompleted && !loadTask.IsCanceled; bool isTimeout = signaledTask.Equals(timeoutTask) && timeoutTask.IsCompleted && !timeoutTask.IsCanceled; // Cancel all incomplete tasks. cancellationTokenSource.Cancel(); int loadedCount = 0; if (loadCompleted) { loadedCount = (int)loadTask.Result; } else if (isTimeout) { // Timeout. throw new System.TimeoutException("ReadPartial was timeout."); } else if (canceledByUser) { throw new OperationCanceledException("ReadPartial was canceled."); } if (loadedCount > 0) { var readBuffer = reader.ReadBuffer((uint)loadedCount); System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(readBuffer, 0, buffer, (uint)offset, (uint)loadedCount); } return loadedCount; }); }