public BeginRead ( byte array, int offset, int numBytes, AsyncCallback callback, object state ) : IAsyncResult | ||
array | byte | |
offset | int | |
numBytes | int | |
callback | AsyncCallback | |
state | object | |
리턴 | IAsyncResult |
public void BeginReadThrowsForWriteOnly() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<NotSupportedException>(() => fs.BeginRead(new byte[0], 0, 0, null, null)); } }
static void Main(string[] args) { //AsyncReadOneFile(); //AsyncReadMultiplyFiles(); FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); Byte[] data = new Byte[100]; IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null); while (!ar.IsCompleted) { Console.WriteLine("Операция не завершена, ожидайте..."); Thread.Sleep(10); } Int32 bytesRead = fs.EndRead(ar); fs.Close(); Console.WriteLine("Количество считаных байт = {0}", bytesRead); Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1)); }
/// <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 BeginReadThrowsForNegativeNumBytes() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<ArgumentOutOfRangeException>("numBytes", () => fs.BeginRead(new byte[0], 0, -1, null, null)); } }
private void ReadFileAsync(Action <byte[]> callback) { _fileStream.BeginRead(_fileBuffer, 0, _fileBuffer.Length, c => { if (this._isStopTask) { return; } int readlenght = _fileStream.EndRead(c); if (readlenght != _fileBuffer.Length) { IsReadEnd(); byte[] buf = new byte[readlenght]; Array.Copy(_fileBuffer, 0, buf, 0, readlenght); callback?.Invoke(buf); } else { IsReadEnd(); callback?.Invoke(_fileBuffer); } void IsReadEnd() { if (_fileStream.Length == _fileStream.Position) { this.CloseFileStream(); } } }, null); }
public void BeginReadThrowsForBadOffset(int arraySize, int offset, int numBytes) { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<ArgumentException>(() => fs.BeginRead(new byte[arraySize], offset, numBytes, null, null)); } }
public void ReadAsync(Action <byte[]> callback) { if (!Exists) { throw new System.IO.IOException("file is not exists"); } //todo:需要测试 System.IO.FileStream fs = new System.IO.FileStream(FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None, bufferSize: 1024, useAsync: true ); byte[] data = new byte[fs.Length]; fs.BeginRead(data, 0, data.Length, (result) => { fs.EndRead(result); data = Decrypted(data); fs.Close(); fs.Dispose(); callback.Invoke(data); }, null); }
public void BeginReadThrowsForNullArray() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<ArgumentNullException>("array", () => fs.BeginRead(null, 0, 0, null, null)); } }
private void BeginAsyncRead() { byte[] arrInputReport = new byte[HidCap.InputReportByteLength]; // put the buff we used to receive the stuff as the async state then we can get at it when the read completes File.BeginRead(arrInputReport, 0, HidCap.InputReportByteLength, new AsyncCallback(ReadCompleted), arrInputReport); }
static void Main(string[] args) { // open filestream for asynchronous read FileStream fs = new FileStream("somedata.dat", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); // byte array to hold 100 bytes of data Byte[] data = new Byte[100]; // initiate asynchronous read operation, reading first 100 bytes IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null); // could do something in here which would run alongside file read... // check for file read complete while (!ar.IsCompleted) { Console.WriteLine("Operation not completed"); Thread.Sleep(10); } // get the result int bytesRead = fs.EndRead(ar); fs.Close(); Console.WriteLine("Number of bytes read={0}", bytesRead); Console.WriteLine(BitConverter.ToString(data, 0, bytesRead)); }
private static void AsyncReadOneFileCallBackAnonimus() { Byte[] data = new Byte[100]; Console.WriteLine("Основной поток ID = {0}", Thread.CurrentThread.ManagedThreadId); FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); fs.BeginRead(data, 0, data.Length, delegate(IAsyncResult ar) { Console.WriteLine("Чтение в потоке {0} закончено", Thread.CurrentThread.ManagedThreadId); Int32 bytesRead = fs.EndRead(ar); fs.Close(); Console.WriteLine("Количество считаных байт = {0}", bytesRead); Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1)); Console.ReadLine(); }, null); Console.ReadLine(); }
public void DownFile(string fileName) { var callback = OperationContext.Current.GetCallbackChannel<IMediaCallBack>(); var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); var customFile = new CustomFile(callback, fs, fileName); fs.BeginRead(customFile.CurrentByte, 0, customFile.MaxLength, DownFileCallBack, customFile); }
public void BeginReadThrowsForClosed() { FileStream fs; using (fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { } Assert.Throws<ObjectDisposedException>(() => fs.BeginRead(new byte[0], 0, 0, null, null)); }
public static void Load(string fileName) { startTime = DateTime.Now; Loaded = 0; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Size = (int)fs.Length; FileData = new byte[Size]; fs.BeginRead(FileData, 0, Size, new AsyncCallback(read), fs); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (_m_disposed) { throw ADP.ObjectDisposed(this); } return(_m_fs.BeginRead(buffer, offset, count, callback, state)); }
static void Main(string[] args) { const string FilePath = @"D:\Downloads\Sygic 13.2.2\Sygic Map Downloader (TomTom 2013.06)\sgcmapdownloader.txt"; FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); IAsyncResult result = fileStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(CompleteRead), fileStream); Console.ReadLine(); }
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); }
void ReadNextBuffer() { if (!readEnabled) { return; } var length = (int)Math.Min(readBuffer.Length, readLimit); stream.BeginRead(readBuffer, 0, length, OnReadDone, null); }
public IAsyncResult BeginProcessRequest ( HttpContext context, AsyncCallback cb, object extraData ) { HttpRequest request = context.Request; m_response = context.Response; lock (m_lock) { m_fileStream = new FileStream(request.MapPath("~/App_Data/TrackerLog.xml"), FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true); m_xmlFragmentByteArray = new byte[m_fileStream.Length]; return m_fileStream.BeginRead(m_xmlFragmentByteArray, 0, (int)m_fileStream.Length, cb, extraData); } }
private void ReplaceFileContent(string file) { var fileStream = new FileStream(file, FileMode.Open); var state = new FileState { FileStream = fileStream, FileName = file, Data = new byte[fileStream.Length] }; fileStream.BeginRead(state.Data, 0, (int)fileStream.Length, ReadDone, state); }
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(); }
private static void AsyncReadOneFileCallBack() { Console.WriteLine("Основной поток ID = {0}", Thread.CurrentThread.ManagedThreadId); FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); fs.BeginRead(staticData, 0, staticData.Length, ReadIsComplete, fs); Console.ReadLine(); }
static void Main(string[] args) { byte[] buf = new byte[128]; FileStream file = new FileStream(@"D:\hello.py", FileMode.Open); IAsyncResult ar = file.BeginRead(buf, 0, 128, null, null); Thread.Sleep(1000); // do other things int n = file.EndRead(ar); file.Close(); string s = Encoding.UTF8.GetString(buf, 0, n); Console.WriteLine("Readed: {0}, {1}", n, s); }
static void Main(string[] args) { const string filePath = @"C:\Apps\Foo.txt"; FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); IAsyncResult result = fileStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(CompleteRead), fileStream); Console.ReadLine(); }
public void BeginLoad() { string path = _uri.PathAndQuery; FileInfo fi = new FileInfo(path); if(fi.Exists) { FileStream fs = new FileStream(path, FileMode.Open); // Create a synchronization object that gets // signaled when read is complete. ManualResetEvent manualEvent = new ManualResetEvent(false); var stateObject = new State(fs, fi.Length, manualEvent); //todo: implement buffer of 4096 size and provide intermediate state notifications fs.BeginRead(stateObject.Buffer, 0, (int)stateObject.BufferSize, new AsyncCallback(EndReadCallback), stateObject); } }
static void DemoAsync() { using (var fs = new FileStream(@"C:\temp\foo.txt", FileMode.Open)) { byte[] content = new byte[fs.Length]; IAsyncResult ar = fs.BeginRead(content, 0, (int)fs.Length, ReadCompletionCallback, null); Console.WriteLine("控制流程回到主執行緒,執行其他工作..."); Thread.Sleep(1500); // 模擬執行其他工作需要花費的時間。 // 等到需要取得結果時,呼叫 EndRead 方法(會 block 當前執行緒) int bytesRead = fs.EndRead(ar); Console.WriteLine("一共讀取了 {0} bytes。", bytesRead); } }
static void Main(string[] args) { // open filestream for asynchronous read FileStream fs = new FileStream("somedata.dat", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); // initiate asynchronous read operation, reading first 100 bytes // pass filestream object (fs) to callback fs.BeginRead(data, 0, data.Length, ReadIsDone, fs); // could do something in here which would run alongside file read... Console.ReadKey(); }
static void Main(string[] args) { //sync var syncStream = new FileStream("file.txt", FileMode.Open); var syncBuffer = new byte[1024]; var syncBytesRead = syncStream.Read(syncBuffer, 0, syncBuffer.Length); Console.WriteLine("Read " + syncBytesRead + " bytes syncronously"); syncStream.Close(); //Async Programming Model stream = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true); buffer = new byte[1024]; var asyncResult = stream.BeginRead(buffer, 0, buffer.Length, FinishedRead, null); //can also poll for status while(!asyncResult.IsCompleted) { Console.WriteLine("Waiting for BeginRead to complete"); } stream.Close(); //Event-based Async Pattern var client = new WebClient(); client.DownloadStringCompleted += ClientOnDownloadStringCompleted; client.DownloadStringAsync(new Uri("http://www.rtigger.com")); while(string.IsNullOrEmpty(downloadedString)) { Console.WriteLine("Waiting for DownloadString to complete"); Thread.Sleep(100); } //Task Async Pattern var stream2 = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true); var buffer2 = new byte[1024]; var result = Task<int>.Factory.FromAsync(stream2.BeginRead, stream2.EndRead, buffer2, 0, buffer2.Length, null); //do other things while task is executing while(!result.IsCompleted) { Console.WriteLine("Waiting for Task to complete"); } Console.WriteLine("Task finished, read " + result.Result + " bytes from file"); //async pattern AsyncContext.Run(() => DownloadStringAsync("http://www.rtigger.com")); Console.ReadLine(); }
//Метод считывания из одного файла private static void AsyncReadOneFile() { FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); Byte[] data = new Byte[100]; // Начало асинхронной операции чтения из файла FileStream. IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null); // Здесь выполняется другой код... // Приостановка этого потока до завершения асинхронной операции // и получения ее результата. Int32 bytesRead = fs.EndRead(ar); // Других операций нет. Закрытие файла. fs.Close(); // Теперь можно обратиться к байтовому массиву и вывести результат операции. Console.WriteLine("Количество прочитаных байт = {0}", bytesRead); Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1)); }
public static string AsyncRead(string filePath) { // string filePath = "c:\\test.txt"; //以只读方式打开文件流 using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.Asynchronous)) { var buffer = new byte[bufferSize]; //构造BeginRead需要传递的状态 AsyncState asyncState = new AsyncState() { FS = fileStream, Buffer = buffer, WaitHandle = new ManualResetEvent(false) }; asyncState.Rs = new List<byte>(); //异步读取 IAsyncResult asyncResult = fileStream.BeginRead(buffer, 0, bufferSize, new AsyncCallback(AsyncReadCallback), asyncState); asyncState.WaitHandle.WaitOne(); //Console.WriteLine("read complete"); return Encoding.UTF8.GetString(asyncState.Rs.ToArray()); } }
static void Main(string[] args) { Callback = new AsyncCallback(CallBackFunction); fileStm = new FileStream("C:\\Users\\admin\\Documents\\Visual Studio 2013\\Projects\\network_programming_for_professionals\\bin\\Debug\\SyncDemo.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 64, true); readbuf = new byte[fileStm.Length]; fileStm.BeginRead(readbuf, 0, readbuf.Length, Callback, null); for(long i=0;i<5000;i++) { if(i%1000==0) { Console.WriteLine("Executing in Main -" + i.ToString()); Thread.Sleep(1000); } } fileStm.Close(); Console.ReadKey(); }
static void Main(string[] args) { // otworz plik var fs = new FileStream("Content.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 512, // otworz plik w trybie asynchronicznym! FileOptions.Asynchronous); buffer = new byte[fs.Length]; // rozpocznij odczyt // UWAGA: ostatni element, stan - przekazuje referencje do strumienia! fs.BeginRead(buffer, 0, buffer.Length, CompleteRead, fs); // zablokujmy glowny watek Console.WriteLine("waiting for complete read... thread: " + Thread.CurrentThread.ManagedThreadId); Console.ReadKey(); }
public static void Main(string[] args) { //sync stream = new FileStream("file.txt", FileMode.Open); var buffer = new byte[1024]; var bytesRead = stream.Read(buffer, 0, buffer.Length); Console.WriteLine("Read " + bytesRead + " from file"); stream.Close(); //APM stream = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true); var asyncResult = stream.BeginRead(buffer, 0, buffer.Length, FinishedRead, null); while (!asyncResult.IsCompleted) { Console.WriteLine("Waiting for begin read to finish"); } //EAP var client = new WebClient(); client.DownloadStringCompleted += OnDownloadStringCompleted; client.DownloadStringAsync(new Uri("http://rtigger.com")); while (string.IsNullOrEmpty(downloadedString)) { Console.WriteLine("Waiting for download string to finish"); } //task stream = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true); var task = Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null); while (!task.IsCompleted) { Console.WriteLine("Waiting for task to finish"); } Console.WriteLine("Task is finished, read " + task.Result + " bytes from file"); AsyncContext.Run(() => DownloadStringAsync("http://www.rtigger.com")); Console.ReadLine(); }
static public int BeginRead(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.BeginRead(a1, a2, a3, a4, a5); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public static string AsyncReadFile(string filePath, Encoding encoding) { if (IsExistFile(filePath)) { try { StringBuilder sb = new StringBuilder(); int bufferSize = 1024; byte[] data = new byte[bufferSize]; FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 20480, true);//设置异步调用true AsyncCallback callback = null; callback = asyncResult => { FileStream read = (FileStream)asyncResult.AsyncState; int bytes=read.EndRead(asyncResult); sb.Append(encoding.GetString(data,0,bytes));//Encoding.ASCII.GetString(data,0,bytes) //System.Threading.Thread.Sleep(2000); if (bytes > 0) { read.BeginRead(data, 0, bufferSize, callback, read); } else { read.Close(); Console.WriteLine(sb.ToString()); } }; IAsyncResult async=fs.BeginRead(data, 0, bufferSize, callback, fs); return sb.ToString(); } catch (Exception ex) { CooperationWrapper.WriteLog(ex); } } throw new FileNotFoundException("file not found"); }
public void Run() { this.output.WriteLine("Thread APM start"); this.CheckFileExists(); var f = new FileInfo(this.sampleLogFileName); this.fileSizeInBytes = f.Length; this.lineSizeInBytesSoFar = 0; this.lineCount = 0; const int Chunksize = 4096; var buffer = new byte[Chunksize]; var sw = new Stopwatch(); sw.Start(); var fs = new FileStream( this.sampleLogFileName, FileMode.Open, FileAccess.Read, FileShare.Read, Chunksize, FileOptions.Asynchronous); fs.BeginRead(buffer, 0, buffer.Length, this.ReadAsyncCallback, new AsyncFileReadInfo(buffer, fs)); this.output.WriteLine(); this.output.WriteLine("All threads started, waiting to complete"); WaitHandle.WaitOne(); sw.Stop(); this.ShowResults(); this.output.WriteLine(); this.output.WriteLine("Thread APM done in {0}", sw.Elapsed); }
protected override void DoRead() { stream.BeginRead(buffer, 0, buffer.Length, OnReadDone, null); }
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 BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return(tempStream.BeginRead(buffer, offset, count, callback, state)); }