public ReadAsync ( byte buffer, int offset, int count, CancellationToken cancellationToken ) : Task |
||
buffer | byte | |
offset | int | |
count | int | |
cancellationToken | CancellationToken | |
return | Task |
public void NegativeOffsetThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], -1, 1))); // buffer is checked first Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.ReadAsync(null, -1, 1))); } }
/// <summary> /// 向客户端异步发送文件 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="filePath"></param> public async Task SendToClientFileAsync(string ip, int port, string filePath, Message msg) { // 新建 Udp 用于发送文件 var sendClient = new UdpClient(); try { FileInfo fileInfo = new FileInfo(filePath); msg.Type = MessageEnum.FILE; // 设置发送文件标识 msg.FileLength = fileInfo.Length; msg.FileName = Regex.Match(filePath, @"\\([^\\]+\.[^\\]+)").Groups[1].Value; // 获取文件名 byte[] datagram = Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(msg)); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port); /* * 向‘原’远程客户端发送请求传送文件的请求, * 接收‘新’远程客户端的响应,获取传送文件的端口 * * 注:原远程客户端用于发送消息,新远程客户端用于发送文件 */ await sendClient.SendAsync(datagram, datagram.Length, endPoint); //IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); UdpReceiveResult result = await sendClient.ReceiveAsync().ConfigureAwait(false); // 阻塞直到接收到远程客户端的响应 /* * 开始发送文件 */ byte[] buffer = new byte[MAXSIZE]; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1, true)) { int percent = 0; int count = 0; while ((count = await fs.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) { //await Task.Delay(10); await sendClient.SendAsync(buffer, count, result.RemoteEndPoint); if (Client.SendFileProgressNotify != null) { Client.SendFileProgressNotify(String.Format("{0:F2}%", (percent += count) / msg.FileLength * 100)); } } sendClient.Close(); } } catch (Exception e) { Log.Write(e.Message); } }
public Task <int> ReadAsync(byte[] btes, int offset, int length) { if (YetaWFManager.IsSync()) { return(Task.FromResult(Stream.Read(btes, offset, length))); } else { return(Stream.ReadAsync(btes, offset, length)); } }
public async Task<IEnumerable<string>> read() { string filePath = @"data/data.csv"; if (File.Exists(filePath) == false) { var emptyList = new List<string>(); Console.WriteLine("file not found: " + filePath); return emptyList; } string data; using (FileStream sourceStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true)) { StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0) { string text = Encoding.UTF8.GetString(buffer, 0, numRead); sb.Append(text); } data = sb.ToString(); } DateTime tempdate; var lines = data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).Where(d => DateTime.TryParse(d.Split(',')[0], out tempdate)); return lines; }
// ----------------------------------------------------------------------- // KEY SAMPLE CODE STARTS HERE // ----------------------------------------------------------------------- private async Task StabilizeVideo(string subscriptionKey, string originalFilePath) { _dataContext.IsWorking = true; _dataContext.SourceUri = null; _dataContext.ResultUri = null; Helpers.Log(LogIdentifier, "Start stabilizing"); Microsoft.ProjectOxford.Video.VideoServiceClient client = new Microsoft.ProjectOxford.Video.VideoServiceClient(subscriptionKey); using (FileStream originalStream = new FileStream(originalFilePath, FileMode.Open, FileAccess.Read)) { byte[] bytes = new byte[originalStream.Length]; await originalStream.ReadAsync(bytes, 0, (int) originalStream.Length); // Creates a video operation of video stabilization Helpers.Log(LogIdentifier, "Start uploading video"); Operation operation = await client.CreateOperationAsync(bytes, OperationType.Stabilize); Helpers.Log(LogIdentifier, "Uploading video done"); // Starts querying service status OperationResult result = await client.GetOperationResultAsync(operation); while (result.Status != OperationStatus.Succeeded && result.Status != OperationStatus.Failed) { Helpers.Log(LogIdentifier, "Server status: {0}, wait {1} seconds...", result.Status, QueryWaitTime.TotalSeconds); await Task.Delay(QueryWaitTime); result = await client.GetOperationResultAsync(operation); } Helpers.Log(LogIdentifier, "Finish processing with server status: " + result.Status); // Processing finished, checks result if (result.Status == OperationStatus.Succeeded) { // Downloads generated video string tmpFilePath = Path.GetTempFileName() + Path.GetExtension(originalFilePath); Helpers.Log(LogIdentifier, "Start downloading result video"); using (Stream resultStream = await client.GetResultVideoAsync(result.ResourceLocation)) using (FileStream stream = new FileStream(tmpFilePath, FileMode.Create)) { byte[] b = new byte[2048]; int length = 0; while ((length = await resultStream.ReadAsync(b, 0, b.Length)) > 0) { await stream.WriteAsync(b, 0, length); } } Helpers.Log(LogIdentifier, "Downloading result video done"); _dataContext.SourceUri = new Uri(originalFilePath); _dataContext.ResultUri = new Uri(tmpFilePath); } else { // Failed Helpers.Log(LogIdentifier, "Fail reason: " + result.Message); } _dataContext.IsWorking = false; } }
public static async Task CopyFiles(string from, string to, ProgressBar bar, Label percent) { long total_size = new FileInfo(from).Length; using (var outStream = new FileStream(to, FileMode.Create, FileAccess.Write)) { using (var inStream = new FileStream(from, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[1024 * 1024]; long total_read = 0; while (total_read < total_size) { int read = await inStream.ReadAsync(buffer, 0, buffer.Length); await outStream.WriteAsync(buffer, 0, read); total_read += read; await System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { long a = total_read * 100 / total_size; bar.Value = a; percent.Content = a + " %"; })); } } } }
private static async Task ReadFileAsync(RetryContext context) { try { using (FileStream stream = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 256, true)) { byte[] buffer = new byte[4]; int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead == buffer.Length) { string text = Encoding.ASCII.GetString(buffer); Log("ReadFileAsync read '{0}'", text); context.Add("Text", text); } else { Log("ReadFileAsync read only {0} bytes.", bytesRead); } } } catch (Exception e) { Log("ReadFileAsync error: {0}: {1}", e.GetType().Name, e.Message); throw; } }
/// <summary> /// 从文件中获取数据包,并将其保存在list中 /// </summary> /// 4G集中器一包512个字节,2G集中器一包1024个字节 public static void GetDataPack(int FileSize, string romPath) { //清空缓存数据包列表 Frm_Main.DataPacks.Clear(); //新建缓存buffer byte[] buffer = new byte[FileSize]; //打开文件 System.IO.FileStream file = new System.IO.FileStream(romPath, FileMode.Open, FileAccess.Read); //句柄 //循环读取文件 while (true) { //加锁 lock (buffer) { //情况缓存buffer Array.Clear(buffer, 0, FileSize); //异步读取文件 Task <int> r = file.ReadAsync(buffer, 0, FileSize); //返回结果为零则表示读取完了 if (r.Result == 0) { file.Close(); return; } //将读取到的buffer封包 Dstruct bufStruct = (Dstruct)UpdateHelper.BytesToStruct(buffer, typeof(Dstruct)); //添加到缓存列表中 DataPacks.Add(bufStruct); } } }
public static async void WritePlayerStat(VehicleHash hash, int data) { string str = encrypt(string.Format("{0}>{1}", (int)hash, data)); using (var fstream = new FileStream("scripts\\driftstats.stat", FileMode.OpenOrCreate)) { int seekPos = 0; byte[] buffer = new byte[24]; while (seekPos < fstream.Length) { fstream.Seek(seekPos, SeekOrigin.Begin); await fstream.ReadAsync(buffer, 0, 24); var line = decrypt(Encoding.ASCII.GetString(buffer)); var keyVal = line.Substring(0, line.IndexOf('>')); var value = line.Substring(line.IndexOf('>') + 1); if (keyVal == ((int)hash).ToString()) { using (StreamWriter writer = new StreamWriter(fstream)) { writer.BaseStream.Seek(seekPos, SeekOrigin.Begin); writer.BaseStream.Write(Encoding.ASCII.GetBytes(str), 0, 24); } return; } seekPos += 24; } } using (StreamWriter writer = File.AppendText("scripts\\driftstats.stat")) { if (writer.BaseStream.CanWrite) writer.Write(str); } }
static async void OpenReadWriteFileAsync(string fileName) { byte[] buffer = null; try { using (Stream streamRead = new FileStream(@fileName, FileMode.Open, FileAccess.Read)) { buffer = new byte[streamRead.Length]; Console.WriteLine("In Read Operation Async"); Task readData = streamRead.ReadAsync(buffer, 0, (int)streamRead.Length); await readData; } using (Stream streamWrite = new FileStream(@"MyFileAsync(bak).txt", FileMode.Create, FileAccess.Write)) { Console.WriteLine("In Write Operation Async "); Task writeData = streamWrite.WriteAsync(buffer, 0, buffer.Length); await writeData; } } catch (Exception) { throw; } }
private async Task<Errorable<Ref>> getRefByName(RefName refName) { FileInfo fiTracker = system.getRefPathByRefName(refName); if (!fiTracker.Exists) return new RefNameDoesNotExistError(refName); byte[] buf; int nr = 0; using (var fs = new FileStream(fiTracker.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, 16384, true)) { // TODO: implement an async buffered Stream: buf = new byte[16384]; nr = await fs.ReadAsync(buf, 0, 16384).ConfigureAwait(continueOnCapturedContext: false); if (nr >= 16384) { // My, what a large tag you have! throw new NotSupportedException(); } } // Parse the CommitID: using (var ms = new MemoryStream(buf, 0, nr, false)) using (var sr = new StreamReader(ms, Encoding.UTF8)) { string line = sr.ReadLine(); if (line == null) return new RefNameDoesNotExistError(refName); var ecid = CommitID.TryParse(line); if (ecid.HasErrors) return ecid.Errors; return (Ref)new Ref.Builder(refName, ecid.Value); } }
private static async Task<JArray> GetPointsArrayAsync(string path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); try { StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = await fs.ReadAsync(buffer, 0, buffer.Length)) != 0) { string text = Encoding.Unicode.GetString(buffer, 0, numRead); sb.Append(text); } return JArray.Parse(sb.ToString()); } catch (IOException e) when (e.HResult == 0x01) { } finally { } return new JArray(); }
private static void CopyAsync(byte[] buffer, FileStream inputStream, Stream outputStream, TaskCompletionSource<object> tcs) { inputStream.ReadAsync(buffer).Then(read => { if (read > 0) { outputStream.WriteAsync(buffer, 0, read) .Then(() => CopyAsync(buffer, inputStream, outputStream, tcs)) .Catch(ex => { inputStream.Close(); outputStream.Close(); tcs.SetException(ex); }); } else { inputStream.Close(); outputStream.Close(); tcs.SetResult(null); } }) .Catch(ex => { inputStream.Close(); outputStream.Close(); tcs.SetException(ex); }); }
public async Task<byte[]> ReadAsync() { using (var input = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) { var result = new byte[input.Length]; await input.ReadAsync(result, 0, (int)input.Length); return result; } }
public void NullBufferThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Throws<ArgumentNullException>("buffer", () => FSAssert.CompletesSynchronously(fs.ReadAsync(null, 0, 1))); } }
public static async Task<byte[]> ReadAllBytesAsync(string Path) { using (var file = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) { byte[] buff = new byte[file.Length]; await file.ReadAsync(buff, 0, (int)file.Length).ConfigureAwait(false); return buff; } }
public async Task<byte[]> GetPhotoInBytes(string photoPath) { byte[] photo; using (var fs = new FileStream(photoPath, FileMode.Open)) { photo = new byte[fs.Length]; await fs.ReadAsync(photo, 0, photo.Length); } return photo; }
private async Task<MemoryStream> ReadStreamAsync(FileStream stream, CancellationToken cancellationToken) { Contract.ThrowIfFalse(stream.Position == 0); byte[] buffer = new byte[(int)stream.Length]; await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); // publiclyVisible must be true to enable optimizations in Roslyn.Compilers.TextUtilities.DetectEncodingAndDecode return new MemoryStream(buffer, index: 0, count: buffer.Length, writable: false, publiclyVisible: true); }
// .NET > 4.5 async static void AsyncDemo() { using (Stream s = new System.IO.FileStream("test.txt", FileMode.Create)) { byte[] block = { 1, 2, 3, 4, 5 }; await s.WriteAsync(block, 0, block.Length); // Выполнить запись асинхронно s.Position = 0; // Переместиться обратно в начало // Читать из потока в массив block: Console.WriteLine(await s.ReadAsync(block, 0, block.Length)); // 5 } }
public async Task <long> ReadAsync(byte[] buffer, long partitionOffset, long bufferOffset, long number, CancellationToken cancellationToken) { using (var filestream = new System.IO.FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { filestream.Position = partitionOffset; Console.WriteLine($"Reading from {filestream.Position} to buffer[{bufferOffset}] {number} bytes of in {path} length = {filestream.Length}");; var size = await filestream.ReadAsync(buffer, (int)bufferOffset, (int)number); Console.WriteLine($"Read: {size} bytes"); return((long)size); } }
public async Task<byte[]> ReadBytes(string path) { byte[] bytes = new byte[0]; using (var fs = new FileStream(path, FileMode.Open)) { bytes = new byte[fs.Length]; await fs.ReadAsync(bytes, 0, (int)fs.Length); } return bytes; }
public static async Task <CroFile> FromFile(string path) { using (var fs = new IO.FileStream(path, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)) { byte[] buffer = new byte[fs.Length]; await fs.ReadAsync(buffer, 0, buffer.Length); CroFile file = new CroFile(path); file.Read(buffer); return(file); } }
private async void ReadFile(int i) { string address = "Assets/Piano Keys Mp3/Piano" + i.ToString() + ".wav"; FileStream fStream = new FileStream(address, FileMode.Open); byte[] buffer = new byte[fStream.Length + 4 - fStream.Length % 4]; await fStream.ReadAsync(buffer, 0, buffer.Length); soundEffects.Add(new SoundEffect(buffer, 44100, AudioChannels.Mono)); fStream.Close(); fStream.Dispose(); soundEffectInstances.Add(soundEffects.Last().CreateInstance()); }
public void BufferOutOfBoundsThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { // offset out of bounds Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 1, 1))); // offset out of bounds for 0 count ReadAsync Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[1], 2, 0))); // offset out of bounds even for 0 length buffer Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], 1, 0))); // combination offset and count out of bounds Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[2], 1, 2))); // edges Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], int.MaxValue, 0))); Assert.Throws<ArgumentException>(null, () => FSAssert.CompletesSynchronously(fs.ReadAsync(new byte[0], int.MaxValue, int.MaxValue))); } }
/// <summary> /// Reads all test async /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static async Task<string> ReadAllTextAsync(string filePath) { using (var sourceStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) { var sb = new StringBuilder(); var buffer = new byte[0x1000]; int numRead; while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0) { string text = Encoding.UTF8.GetString(buffer, 0, numRead); sb.Append(text); } return sb.ToString(); } }
public async Task<byte[]> ReadFileAsync (string aFileName, int length) { byte[] data = new byte[length]; using (FileStream stream = new FileStream (aFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 4, true)) { await stream.ReadAsync (data, 0, data.Length); } return data; }
public async Task<byte[]> Load([NotNull] string fileName) { using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate)) { if (fs.Length == 0) { return null; } byte[] buffer = new byte[fs.Length]; await fs.ReadAsync(buffer, 0, (int)fs.Length); return buffer; } }
private static async Task<byte[]> ReadBytesAsync(FileStream file, int offset, int count) { file.Position = offset; offset = 0; var buffer = new byte[count]; int read; while (count > 0 && (read = await file.ReadAsync(buffer, offset, count).ConfigureAwait(false)) > 0) { offset += read; count -= read; } if (count < 0) throw new EndOfStreamException(); return buffer; }
public async Task<BigEndianBinaryAccessor> LoadROMAsync() { using(FileStream fs = new FileStream(romPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) { byte[] rom = new byte[fs.Length]; await fs.ReadAsync(rom, 0, rom.Length); BigEndianBinaryAccessor accessor = new BigEndianBinaryAccessor(rom); if (!validator.IsValidROM(accessor)) throw new ApplicationException("Invalid ROM format"); return accessor; } }
public async Task<FileParserResult> ParseEntireContentAsync() { byte[] content; int readBytes; using (var fileStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.None, DefaultBufferSize, FileOptions.Asynchronous)) { content = new byte[fileStream.Length]; readBytes = await fileStream.ReadAsync(content, 0, content.Length); } using (var memoryStream = new MemoryStream(content, 0, readBytes, false)) { return this.ReadEntireContentFromStream(memoryStream); } }
/// <summary> /// Reads DB file /// </summary> /// <returns>File content as UTF8 string.</returns> private async Task<String> ReadDB(){ try { using (FileStream sourceStream = new FileStream(DBFileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true)) { byte[] buffer = new byte[sourceStream.Length]; int bytes = await sourceStream.ReadAsync(buffer, 0, buffer.Length, CancellationToken); return Encoding.UTF8.GetString(buffer, 0, bytes); } } catch (IOException e) { Logger.Error(e); } return null; }
public async Task Perform() { using (var sourceStream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous)) { byte[] fileContent = new byte[sourceStream.Length]; await sourceStream.ReadAsync(fileContent, 0, fileContent.Length); var message = new FileMessage { FileContent = fileContent, FileName = System.IO.Path.GetFileName(this.Path), OperationType = OperationType.Changed }; _fileSender.Send(message); } }
// ----------------------------------------------------------------------- // KEY SAMPLE CODE STARTS HERE // ----------------------------------------------------------------------- private async Task DetectFaces(string subscriptionKey, string filePath) { _dataContext.IsWorking = true; _dataContext.SourceUri = null; _dataContext.ResultText = null; Helpers.Log(LogIdentifier, "Start face tracking"); Microsoft.ProjectOxford.Video.VideoServiceClient client = new Microsoft.ProjectOxford.Video.VideoServiceClient(subscriptionKey); using (FileStream originalStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] bytes = new byte[originalStream.Length]; await originalStream.ReadAsync(bytes, 0, (int)originalStream.Length); // Creates a video operation of face tracking Helpers.Log(LogIdentifier, "Start uploading video"); Operation operation = await client.CreateOperationAsync(bytes, OperationType.TrackFace); Helpers.Log(LogIdentifier, "Uploading video done"); // Starts querying service status OperationResult result = await client.GetOperationResultAsync(operation); while (result.Status != OperationStatus.Succeeded && result.Status != OperationStatus.Failed) { Helpers.Log(LogIdentifier, "Server status: {0}, wait {1} seconds...", result.Status, QueryWaitTime.TotalSeconds); await Task.Delay(QueryWaitTime); result = await client.GetOperationResultAsync(operation); } Helpers.Log(LogIdentifier, "Finish processing with server status: " + result.Status); // Processing finished, checks result if (result.Status == OperationStatus.Succeeded) { // Gets output JSON Helpers.Log(LogIdentifier, "Downloading result done"); _dataContext.SourceUri = new Uri(filePath); _dataContext.ResultText = Helpers.FormatJson<FaceTracking>(result.ProcessingResult); _dataContext.FrameHighlights = GetHighlights(result.ProcessingResult).ToList(); } else { // Failed Helpers.Log(LogIdentifier, "Fail reason: " + result.Message); } _dataContext.IsWorking = false; } }
public async Task<FileMetadata> ParseMetadataAsync() { FileMetadata result; byte[] metadataContent = new byte[FileMetadata.Size]; using (var fileStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.None, DefaultBufferSize, FileOptions.Asynchronous)) { await fileStream.ReadAsync(metadataContent, 0, FileMetadata.Size); } using (var memoryStream = new MemoryStream(metadataContent, false)) { result = this.ReadMetadataFromStream(memoryStream); } return result; }
private async Task<string> ReadTextAsync(string filePath) { using (FileStream sourceStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true)) { StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[4096]; int numRead; while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0) { string text = Encoding.UTF8.GetString(buffer, 0, numRead); sb.Append(text); } return sb.ToString(); } }
private async Task LoadFrameImage(System.IO.FileInfo imageFile, GameObject frameImage) { Debug.LogFormat("#1 LoadFrameImage {2} - t: {0}, dt: {1}", Time.unscaledTime, Time.deltaTime, imageFile.Name); System.IO.FileStream file = imageFile.OpenRead(); byte[] fileData = new byte[file.Length]; Debug.LogFormat("#2 LoadFrameImage {2} - t: {0}, dt: {1}", Time.unscaledTime, Time.deltaTime, imageFile.Name); await file.ReadAsync(fileData, 0, (int)file.Length); Debug.LogFormat("#3 LoadFrameImage {2} - t: {0}, dt: {1}", Time.unscaledTime, Time.deltaTime, imageFile.Name); // Load Image prend trop de temps et bloque le jeu. var tex = new Texture2D(2, 2); tex.LoadImage(fileData); //..this will auto-resize the texture dimensions. Debug.LogFormat("#4 LoadFrameImage {2} - t: {0}, dt: {1}", Time.unscaledTime, Time.deltaTime, imageFile.Name); //Debug.Log("Image found : " + image + " Load Texture : " + listOfImages[loadedImage].Name); frameImage.GetComponent <Renderer>().material.SetTexture("_MainTex", tex); // Debug.Log(string.Format("Texture width {0}, height {1}", tex.width, tex.height)); Debug.LogFormat("#5 LoadFrameImage {2} - t: {0}, dt: {1}", Time.unscaledTime, Time.deltaTime, imageFile.Name); //Get ratio : var ratio = tex.width / tex.height; // TODO Pour les images trop longue en hauteur ou en largeur les limités !!! if (tex.width > tex.height) { frameImage.transform.localScale = new Vector3(frameImage.transform.localScale.x * ((float)tex.width / (float)tex.height), 1, frameImage.transform.localScale.z); } else if (tex.height > tex.width) { // Comme l'image a son ancre au centre on doit remonter un peu l'image si on l'etire dans le sens de la hauteur. (10 egale le nombre d'unité par défaut) frameImage.transform.localPosition = new Vector3( frameImage.transform.localPosition.x, ((frameImage.transform.localScale.z * ((float)tex.height / (float)tex.width) - (float)frameImage.transform.localScale.z) / 2) * 10, frameImage.transform.localPosition.z); frameImage.transform.localScale = new Vector3(frameImage.transform.localScale.x, 1, frameImage.transform.localScale.z * ((float)tex.height / (float)tex.width)); } }
static public int ReadAsync(IntPtr l) { try { System.IO.FileStream self = (System.IO.FileStream)checkSelf(l); System.Byte[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Threading.CancellationToken a4; checkValueType(l, 5, out a4); var ret = self.ReadAsync(a1, a2, a3, a4); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
//private byte[] buffer = null; public async void Send(ushort playerId, string fileName, System.IO.FileStream fileStream) { if (fileStream.Length <= NetworkLinkerPool.MTU - HeaderSize) { Debug.LogError("MTU以下のサイズのデータは送れません"); return; } int hash = FileToHash(fileStream); var transporter = new FileTransporter(hash, fileName, fileStream, SendBytePerFrame, 0); int nameByteCount = DataStreamWriter.GetByteSizeStr(fileName); int dataSize = NetworkLinkerPool.MTU - HeaderSize - 15 - nameByteCount; fileStream.Seek(0, SeekOrigin.Begin); int readSize = await fileStream.ReadAsync(transporter.buffer, 0, dataSize); //Debug.Log ("Start : " + string.Join ("", transporter.buffer)); unsafe { fixed(byte *dataPtr = transporter.buffer) { using (var writer = new DataStreamWriter(dataSize + 15 + nameByteCount, Allocator.Temp)) { writer.Write((byte)BuiltInPacket.Type.DataTransporter); writer.Write((byte)TransporterType.File); writer.Write(hash); writer.Write((byte)FlagDef.Start); writer.Write(fileName); writer.Write((int)fileStream.Length); writer.Write((ushort)dataSize); writer.WriteBytes(dataPtr, dataSize); NetworkManager.Brodcast(writer, QosType.Reliable, true); } } } transporter.pos += dataSize; sendTransporterTable[hash] = transporter; }
public static async Task <T> ReadFile <T>(string path) where T : class { try { await fileStreamSemaphore.WaitAsync(); if (!System.IO.File.Exists(path)) { return(null); } string serializedContent = string.Empty; using (var sourceStream = new System.IO.FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true)) { StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0) { sb.Append(Encoding.Unicode.GetString(buffer, 0, numRead)); } serializedContent = sb.ToString(); } if (string.IsNullOrEmpty(serializedContent)) { return(null); } var value = Deserialize <T>(serializedContent); return(value); } catch (Exception) { throw; } finally { fileStreamSemaphore.Release(); } }
public override Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return(tempStream.ReadAsync(buffer, offset, count, cancellationToken)); }