private async void StartReceiveDataAsync() { // bắt đầu nhận dữ liệu về // kiểm tra đã đủ 4 byte chưa uint size = await reader.LoadAsync(sizeof(int)); if (size != sizeof(uint)) { Disconnect(); return; } byte[] fourbytefirst = new byte[4]; // đủ rồi thì đọc 4 byte đầu lên để xem kích thước dữ liệu reader.ReadBytes(fourbytefirst); int Packagesize = BitConverter.ToInt32(fourbytefirst, 0); // kiểm tra xem dữ liệu đã về đủ hết chưa uint datalength = await reader.LoadAsync((uint)Packagesize); if (datalength != Packagesize) { Disconnect(); return; } // đủ rồi thì tạo mảng byte để lưu dữ liệu byte[] data = new byte[datalength]; reader.ReadBytes(data); DataReceived(data); StartReceiveDataAsync(); }
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; } } }
/// <summary> /// ReadAsync: Task that waits on data and reads asynchronously from the serial device InputStream /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <byte[]> Read() { Task <UInt32> loadAsyncTask; uint ReadBufferLength = 1024; // If task cancellation was requested, comply this.ReadCancellationTokenSource.Token.ThrowIfCancellationRequested(); // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available dataReaderObject.InputStreamOptions = Windows.Storage.Streams.InputStreamOptions.Partial; // Create a task object to wait for data on the serialPort.InputStream loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(this.ReadCancellationTokenSource.Token); // Launch the task and wait UInt32 bytesRead = await loadAsyncTask; byte[] data = new byte[bytesRead]; if (bytesRead > 0) { dataReaderObject.ReadBytes(data); } if (NotifyMessageReceivedEvent != null) { NotifyMessageReceivedEvent(this, data); } return(data); }
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 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); } } }
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; }
/// <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); }
private async Task <byte[]> ReceiveDataAsync() { // bắt đầu nhận dữ liệu về // kiểm tra đã đủ 4 byte chưa uint size = await reader.LoadAsync(sizeof(int)); System.Diagnostics.Debug.WriteLine("Load 1"); if (size != sizeof(uint)) { Disconnect(); return(null); } byte[] fourbytefirst = new byte[4]; // đủ rồi thì đọc 4 byte đầu lên để xem kích thước dữ liệu reader.ReadBytes(fourbytefirst); int Packagesize = BitConverter.ToInt32(fourbytefirst, 0); // kiểm tra xem dữ liệu đã về đủ hết chưa uint datalength = await reader.LoadAsync((uint)Packagesize); System.Diagnostics.Debug.WriteLine("Load 2"); if (datalength != Packagesize) { Disconnect(); return(null); } System.Diagnostics.Debug.WriteLine("Load 3"); // đủ rồi thì tạo mảng byte để lưu dữ liệu byte[] data = new byte[datalength]; System.Diagnostics.Debug.WriteLine("Load 4"); reader.ReadBytes(data); System.Diagnostics.Debug.WriteLine("Load 5"); return(data); }
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)); }
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); }
/// <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); }
public static async Task <byte[]> GetBytesAsync(StorageFile file) { byte[] fileBytes = null; if (file == null) { return(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); }
private static string GetAppSpecificHardwareID() { Windows.System.Profile.HardwareToken packageSpecificToken; try { packageSpecificToken = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null); if (packageSpecificToken != null) { Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(packageSpecificToken.Id); byte[] bytes = new byte[packageSpecificToken.Id.Length]; dataReader.ReadBytes(bytes); return(BitConverter.ToString(bytes)); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception in GetAppSpecificHardwareID: " + e.Message); } return("UNKNOWN"); }
public async Task <string> GetData(Windows.Storage.Streams.IBuffer data) { try { StringBuilder result = new StringBuilder(); if (data == null) { result.Append("No data"); } else { const uint MAX_BYTES_TO_PRINT = 20; uint bytesToPrint = Math.Min(data.Length, MAX_BYTES_TO_PRINT); Windows.Storage.Streams.DataReader reader = Windows.Storage.Streams.DataReader.FromBuffer(data); byte[] dataBytes = new byte[bytesToPrint]; reader.ReadBytes(dataBytes); for (uint byteIndex = 0; byteIndex < bytesToPrint; ++byteIndex) { result.AppendFormat("{0:X2} ", dataBytes[byteIndex]); } if (bytesToPrint < data.Length) { result.Append("..."); } } return(result.ToString()); } catch (Exception ex) { MessagingCenter.Send <xx.App, string>((xx.App)obj.xxApp, "exception", "ScrannerInit/GetData IBuffer: " + ex.Message); return(""); } }
public async Task <string> GetData(Windows.Storage.Streams.IBuffer data) { try { StringBuilder result = new StringBuilder(); if (data == null) { result.Append("No data"); } else { const uint MAX_BYTES_TO_PRINT = 20; uint bytesToPrint = Math.Min(data.Length, MAX_BYTES_TO_PRINT); Windows.Storage.Streams.DataReader reader = Windows.Storage.Streams.DataReader.FromBuffer(data); byte[] dataBytes = new byte[bytesToPrint]; reader.ReadBytes(dataBytes); for (uint byteIndex = 0; byteIndex < bytesToPrint; ++byteIndex) { result.AppendFormat("{0:X2} ", dataBytes[byteIndex]); } if (bytesToPrint < data.Length) { result.Append("..."); } } return(result.ToString()); } catch (Exception ex) { //await DisplayAlert("Error", "GetData failed, Code:" + " Message:" + ex.Message, "OK"); return(""); } }
private async void Downloader_ImgLoadedProcess(string value, IStorageFile file) { String javascript = "img_replace_by_url"; string base64 = string.Empty; try { using (var stream = await file.OpenAsync(FileAccessMode.Read)) { var reader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); var bytes = new byte[stream.Size]; await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(bytes); base64 = Convert.ToBase64String(bytes); } await webView.InvokeScriptAsync(javascript, new string[] { $"{value}", $"data:image/png; base64,{base64}" }); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } }
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 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; }
async void beginexecblock() { if ((await Windows.Storage.ApplicationData.Current.RoamingFolder.GetFilesAsync()).Count == 0) { await ApplicationData.Current.RoamingFolder.CreateFileAsync("testfile.txt"); ApplicationData.Current.SignalDataChanged(); Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog("Roaming file creation success", "Sync status"); await tdlg.ShowAsync(); } try { DateTime started = DateTime.Now; RenderContext mtext = new RenderContext(); maincontext = mtext; StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation; StorageFile file = await folder.GetFileAsync("DXInteropLib\\VertexShader.cso"); var stream = (await file.OpenAsync(FileAccessMode.Read)); Windows.Storage.Streams.DataReader mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); byte[] dgram = new byte[file.Size]; await mreader.LoadAsync((uint)dgram.Length); mreader.ReadBytes(dgram); file = await folder.GetFileAsync("DXInteropLib\\PixelShader.cso"); stream = await file.OpenAsync(FileAccessMode.Read); mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); byte[] mgram = new byte[file.Size]; await mreader.LoadAsync((uint)file.Size); mreader.ReadBytes(mgram); try { defaultshader = mtext.CreateShader(dgram, mgram); mtext.InitializeLayout(dgram); defaultshader.Apply(); mtext.OnRenderFrame += onrenderframe; } catch (Exception er) { Windows.UI.Popups.MessageDialog mdlg = new Windows.UI.Popups.MessageDialog(er.ToString(),"Fatal error"); mdlg.ShowAsync().Start(); } IStorageFile[] files = (await folder.GetFilesAsync()).ToArray(); bool founddata = false; foreach (IStorageFile et in files) { if (et.FileName.Contains("rawimage.dat")) { stream = await et.OpenAsync(FileAccessMode.Read); founddata = true; } } int width; int height; byte[] rawdata; if (!founddata) { file = await folder.GetFileAsync("TestProgram\\test.png"); stream = await file.OpenAsync(FileAccessMode.Read); var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream); var pixeldata = await decoder.GetPixelDataAsync(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.IgnoreExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.DoNotColorManage); width = (int)decoder.PixelWidth; height = (int)decoder.PixelHeight; rawdata = pixeldata.DetachPixelData(); file = await folder.CreateFileAsync("rawimage.dat"); stream = (await file.OpenAsync(FileAccessMode.ReadWrite)); var realstream = stream.GetOutputStreamAt(0); DataWriter mwriter = new DataWriter(realstream); mwriter.WriteInt32(width); mwriter.WriteInt32(height); mwriter.WriteBytes(rawdata); await mwriter.StoreAsync(); await realstream.FlushAsync(); } else { DataReader treader = new DataReader(stream.GetInputStreamAt(0)); await treader.LoadAsync((uint)stream.Size); rawdata = new byte[stream.Size-(sizeof(int)*2)]; width = treader.ReadInt32(); height = treader.ReadInt32(); treader.ReadBytes(rawdata); } Texture2D mtex = maincontext.createTexture2D(rawdata, width, height); List<VertexPositionNormalTexture> triangle = new List<VertexPositionNormalTexture>(); triangle.Add(new VertexPositionNormalTexture(new Vector3(-.5f,-.5f,0),new Vector3(1,1,1),new Vector2(0,0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(0,0.5f,0),new Vector3(1,1,1),new Vector2(1,0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(.5f,-0.5f,0),new Vector3(1,1,1),new Vector2(1,1))); byte[] gpudata = VertexPositionNormalTexture.Serialize(triangle.ToArray()); VertexBuffer mbuffer = maincontext.createVertexBuffer(gpudata,VertexPositionNormalTexture.Size); mbuffer.Apply(VertexPositionNormalTexture.Size); vertcount = 3; Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog("Unit tests successfully completed\nShader creation: Success\nTexture load: Success\nVertex buffer creation: Success\nTime:"+(DateTime.Now-started).ToString(), "Results"); tdlg.ShowAsync().Start(); } catch (Exception er) { Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog(er.ToString(), "Fatal error"); tdlg.ShowAsync().Start(); } }
/// <summary> /// Imports a glTF object from the provided uri. /// </summary> /// <param name="uri">the path to the file to load</param> /// <returns>New <see cref="GltfObject"/> imported from uri.</returns> /// <remarks> /// Must be called from the main thread. /// If the <see cref="Application.isPlaying"/> is false, then this method will run synchronously. /// </remarks> public static async Task <GltfObject> ImportGltfObjectFromPathAsync(string uri) { if (!SyncContextUtility.IsMainThread) { Debug.LogError("ImportGltfObjectFromPathAsync must be called from the main thread!"); return(null); } if (string.IsNullOrWhiteSpace(uri)) { Debug.LogError("Uri is not valid."); return(null); } GltfObject gltfObject; bool isGlb = false; bool loadAsynchronously = Application.isPlaying; if (loadAsynchronously) { await Awaiters.BackgroundThread; } if (uri.EndsWith(".gltf")) { string gltfJson = File.ReadAllText(uri); gltfObject = GetGltfObjectFromJson(gltfJson); if (gltfObject == null) { Debug.LogError("Failed load Gltf Object from json schema."); return(null); } } else if (uri.EndsWith(".glb")) { isGlb = true; byte[] glbData; #if WINDOWS_UWP if (loadAsynchronously) { try { var storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(uri); if (storageFile == null) { Debug.LogError($"Failed to locate .glb file at {uri}"); return(null); } var buffer = await Windows.Storage.FileIO.ReadBufferAsync(storageFile); using (Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)) { glbData = new byte[buffer.Length]; dataReader.ReadBytes(glbData); } } catch (Exception e) { Debug.LogError(e.Message); return(null); } } else { glbData = UnityEngine.Windows.File.ReadAllBytes(uri); } #else using (var stream = File.Open(uri, FileMode.Open)) { glbData = new byte[stream.Length]; if (loadAsynchronously) { await stream.ReadAsync(glbData, 0, (int)stream.Length); } else { stream.Read(glbData, 0, (int)stream.Length); } } #endif gltfObject = GetGltfObjectFromGlb(glbData); if (gltfObject == null) { Debug.LogError("Failed to load GlTF Object from .glb!"); return(null); } } else { Debug.LogError("Unsupported file name extension."); return(null); } gltfObject.Uri = uri; int nameStart = uri.Replace("\\", "/").LastIndexOf("/", StringComparison.Ordinal) + 1; int nameLength = uri.Length - nameStart; gltfObject.Name = uri.Substring(nameStart, nameLength).Replace(isGlb ? ".glb" : ".gltf", string.Empty); gltfObject.LoadAsynchronously = loadAsynchronously; await gltfObject.ConstructAsync(); if (gltfObject.GameObjectReference == null) { Debug.LogError("Failed to construct glTF Object."); } if (loadAsynchronously) { await Awaiters.UnityMainThread; } return(gltfObject); }
/// <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; } }
private static async Task ConstructTextureAsync(this GltfObject gltfObject, GltfTexture gltfTexture) { if (gltfObject.LoadAsynchronously) { await Awaiters.BackgroundThread; } if (gltfTexture.source >= 0) { GltfImage gltfImage = gltfObject.images[gltfTexture.source]; byte[] imageData = null; Texture2D texture = null; if (!string.IsNullOrEmpty(gltfObject.Uri) && !string.IsNullOrEmpty(gltfImage.uri)) { var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName; var path = $"{parentDirectory}\\{gltfImage.uri}"; #if UNITY_EDITOR if (gltfObject.LoadAsynchronously) { await Awaiters.UnityMainThread; } var projectPath = path.Replace("\\", "/"); projectPath = projectPath.Replace(Application.dataPath, "Assets"); texture = UnityEditor.AssetDatabase.LoadAssetAtPath <Texture2D>(projectPath); if (gltfObject.LoadAsynchronously) { await Awaiters.BackgroundThread; } #endif if (texture == null) { #if WINDOWS_UWP if (gltfObject.LoadAsynchronously) { try { var storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(path); if (storageFile != null) { var buffer = await Windows.Storage.FileIO.ReadBufferAsync(storageFile); using (Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)) { imageData = new byte[buffer.Length]; dataReader.ReadBytes(imageData); } } } catch (Exception e) { Debug.LogError(e.Message); } } else { imageData = UnityEngine.Windows.File.ReadAllBytes(path); } #else using (FileStream stream = File.Open(path, FileMode.Open)) { imageData = new byte[stream.Length]; if (gltfObject.LoadAsynchronously) { await stream.ReadAsync(imageData, 0, (int)stream.Length); } else { stream.Read(imageData, 0, (int)stream.Length); } } #endif } } else { var imageBufferView = gltfObject.bufferViews[gltfImage.bufferView]; imageData = new byte[imageBufferView.byteLength]; Array.Copy(imageBufferView.Buffer.BufferData, imageBufferView.byteOffset, imageData, 0, imageData.Length); } if (texture == null) { if (gltfObject.LoadAsynchronously) { await Awaiters.UnityMainThread; } // TODO Load texture async texture = new Texture2D(2, 2); gltfImage.Texture = texture; gltfImage.Texture.LoadImage(imageData); } else { gltfImage.Texture = texture; } gltfTexture.Texture = texture; if (gltfObject.LoadAsynchronously) { await Awaiters.BackgroundThread; } } }
/// <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; }