private static async Task <byte[]> CreateHashBufferAsync(string sourceFilePath, int length) { byte[] data; var fi = new System.IO.FileInfo(sourceFilePath); if (fi.Length < length * 3) { data = await System.IO.File.ReadAllBytesAsync(fi.FullName); } else { data = new byte[length * 3]; using (System.IO.FileStream fs = new System.IO.FileStream(sourceFilePath, System.IO.FileMode.Open)) { // First n bytes await fs.ReadAsync(data, 0, length); // Middle + n bytes fs.Seek(fs.Length / 2, System.IO.SeekOrigin.Begin); await fs.ReadAsync(data, length, length); // End - n bytes fs.Seek(fs.Length - length, System.IO.SeekOrigin.Begin); await fs.ReadAsync(data, length * 2, length); } } return(data); }
static int _m_ReadAsync(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.IO.FileStream gen_to_be_invoked = (System.IO.FileStream)translator.FastGetCSObj(L, 1); { byte[] _buffer = LuaAPI.lua_tobytes(L, 2); int _offset = LuaAPI.xlua_tointeger(L, 3); int _count = LuaAPI.xlua_tointeger(L, 4); System.Threading.CancellationToken _cancellationToken; translator.Get(L, 5, out _cancellationToken); System.Threading.Tasks.Task <int> gen_ret = gen_to_be_invoked.ReadAsync(_buffer, _offset, _count, _cancellationToken); translator.Push(L, gen_ret); return(1); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } }
public async Task <HidDeviceReport> GetReportAsync(CancellationToken token) { var buffer = ArrayPool <byte> .Shared.Rent(capabilities.InputReportByteLength); var status = HidDeviceReport.ReadStatus.NoDataRead; try { using (var device = new DeviceContext(Path, accessMode: DeviceContext.AccessModeType.GenericRead | DeviceContext.AccessModeType.GenericWrite)) { using (var fileHandle = new SafeFileHandle(device.Handle, false)) { using (var fs = new System.IO.FileStream(fileHandle, System.IO.FileAccess.Read, buffer.Length, true)) { await fs.ReadAsync(buffer, 0, buffer.Length, token); } } var newBuffer = new byte[capabilities.InputReportByteLength]; Array.Copy(buffer, 0, newBuffer, 0, newBuffer.Length); return(new HidDeviceReport(newBuffer, HidDeviceReport.ReadStatus.Success)); } } catch { status = HidDeviceReport.ReadStatus.ReadError; } finally { ArrayPool <byte> .Shared.Return(buffer); } return(new HidDeviceReport(status)); }
protected override async void StreamThread() { if (System.IO.File.Exists(this.filename)) { File body = new File(); long contentlong = 0; label.Text = "0%"; label.Name = "label"; label.AutoSize = true; progress.Value = 0; progress.Maximum = 100; progress.Controls.Add(label); progress.Size = new System.Drawing.Size(181, 23); body.Title = System.IO.Path.GetFileName(this.filename); body.Description = "File uploaded by 클라우드 통합관리"; body.MimeType = DaimtoGoogleDriveHelper.GetMimeType(this.filename); body.Parents = new List <ParentReference>() { new ParentReference() { Id = this.Parent } }; FilesResource.InsertMediaUpload request = null; this.OnControl(this, progress, label); byte[] byteArray = new byte[this.StreamBlockSize]; int ReadSize = 0; System.IO.MemoryStream mstream = new System.IO.MemoryStream(); try { while ((ReadSize = await realfile.ReadAsync(byteArray, 0, this.StreamBlockSize, CancellationToken.None)) > 0) { mstream.Capacity = ReadSize; contentlong += ReadSize; request = this.service.Files.Insert(body, mstream, DaimtoGoogleDriveHelper.GetMimeType(this.filename)); this.OnProgressChange(this, maxsize, contentlong, this.progress); } request.Upload(); realfile.Close(); mstream.Close(); this.OnComplete(this, progress); } catch (Exception e) { MessageBox.Show("오류: " + e.Message); return; } } else { MessageBox.Show("파일이 존재하지 않습니다: " + this.filename); return; } }
public async Task <FileResult> GetSlide(int id) { ScreenSaverItem screenSaverItem = await db.ScreenSaverItems.FindAsync(id); using (var slidefile = new System.IO.FileStream(screenSaverItem.SlidesPath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { byte[] data = new byte[slidefile.Length]; await slidefile.ReadAsync(data, 0, data.Length); return(File(data, System.Net.Mime.MediaTypeNames.Application.Octet, screenSaverItem.Name + ".pptx")); } }
protected internal async void SendFile(string RemoteSeverName, int intFileSendPort, string sFullPathToFile) //Send file to _textBoxClientIpText():_numericUpDownClien() { client = new System.Net.Sockets.TcpClient(RemoteSeverName, intFileSendPort); try { using (System.IO.FileStream inputStream = System.IO.File.OpenRead(sFullPathToFile)) { using (System.Net.Sockets.NetworkStream outputStream = client.GetStream()) { using (var cancellationTokenSource = new System.Threading.CancellationTokenSource(5000)) { using (cancellationTokenSource.Token.Register(() => outputStream.Close())) { using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(outputStream)) { long lenght = inputStream.Length; long totalBytes = 0; int readBytes = 0; byte[] buffer = new byte[1024]; try { writer.Write(System.IO.Path.GetFileName(sFullPathToFile)); writer.Write(lenght); do { readBytes = await inputStream.ReadAsync(buffer, 0, buffer.Length); await outputStream.WriteAsync(buffer, 0, readBytes, cancellationTokenSource.Token); totalBytes += readBytes; } while (client.Connected && totalBytes < lenght); } catch (TimeoutException e) { readBytes = -1; } } } } } } } catch (Exception expt) { Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + "Can't send file to " + RemoteSeverName + ": " + expt.Message); } client.Close(); }
public override Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return(InternalFileStream.ReadAsync(buffer, offset, count)); }
private static async System.Threading.Tasks.Task <ResultType> TaskMain(Fee.File.OnFileTask_CallBackInterface a_callback_interface, Path a_path, Fee.TaskW.CancelToken a_cancel) #endif { ResultType t_ret; { t_ret.binary = null; t_ret.errorstring = null; } Fee.TaskW.TaskW.GetInstance().Post((a_state) => { a_callback_interface.OnFileTask(0.1f); }, null); System.IO.FileStream t_filestream = null; try{ //ファイルパス。 System.IO.FileInfo t_fileinfo = new System.IO.FileInfo(a_path.GetPath()); //開く。 t_filestream = t_fileinfo.OpenRead(); //読み込み。 if (t_filestream != null) { t_ret.binary = new byte[t_filestream.Length]; if (Config.USE_ASYNC == true) { #if ((UNITY_5) || (UNITY_WEBGL)) Tool.Assert(false); #else await t_filestream.ReadAsync(t_ret.binary, 0, t_ret.binary.Length, a_cancel.GetToken()); await t_filestream.FlushAsync(a_cancel.GetToken()); #endif } else { t_filestream.Read(t_ret.binary, 0, t_ret.binary.Length); } } }catch (System.Exception t_exception) { t_ret.binary = null; t_ret.errorstring = "Task_LoadLocalBinaryFile : " + t_exception.Message; } //閉じる。 if (t_filestream != null) { t_filestream.Close(); } if (a_cancel.IsCancellationRequested() == true) { t_ret.binary = null; t_ret.errorstring = "Task_LoadLocalBinaryFile : Cancel"; a_cancel.ThrowIfCancellationRequested(); } if (t_ret.binary == null) { if (t_ret.errorstring == null) { t_ret.errorstring = "Task_LoadLocalBinaryFile : null"; } } return(t_ret); }
public async Task ReadUninsFile() { try { RegistryKey SoftwareKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32); Microsoft.Win32.RegistryKey orbKey = SoftwareKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Osu! Random Beatmap", true); if (orbKey == null) { System.Windows.Forms.MessageBox.Show("ORB is not installed. If it is, the program may be not properly installed. You should try to install it again.", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); Environment.Exit(-1); } else { string[] valueNames = orbKey.GetValueNames(); foreach (var valueName in valueNames) { _valueNamesBackup.Add(valueName, orbKey.GetValue(valueName)); } Path = (string)orbKey.GetValue("InstallLocation"); string dataPath = Path + "unins.dat"; string[] exes = Utils.GetAllFilesFromPath(Path).Where(x => { if (x.Length > 4) { if (x.Substring(x.Length - 4, 4) == ".exe") { return(true); } else { return(false); } } else { return(false); } }).ToArray(); foreach (var exe in exes) { await Utils.CloseProcesses(Utils.CalculateSHA512FromPath(exe), exe); } using (System.IO.FileStream fs = new System.IO.FileStream(dataPath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { while (fs.Position <= fs.Length - 1) { byte[] type = new byte[1]; byte[] filenameLength = new byte[2]; byte[] filename; await fs.ReadAsync(type, 0, type.Length); await fs.ReadAsync(filenameLength, 0, filenameLength.Length); ushort length = BitConverter.ToUInt16(filenameLength, 0); filename = new byte[length]; await fs.ReadAsync(filename, 0, filename.Length); string encodedFilename = Encoding.UTF8.GetString(filename); if (type[0] == 0) { byte[] hash = new byte[64]; await fs.ReadAsync(hash, 0, hash.Length); if (Utils.CalculateSHA512BytesFromPath(encodedFilename).SequenceEqual(hash)) { _componentsToUninstall.Add(encodedFilename, type[0]); } } else { _componentsToUninstall.Add(encodedFilename, type[0]); } } } } Percentage += 2500; } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Oops, that's so embarrassing... An error occurred: " + e.ToString(), "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); CurrentDescription = "Operations rollback..."; await OperationsRollback(); Environment.Exit(e.HResult); } }