EndWrite() публичный метод

public EndWrite ( IAsyncResult asyncResult ) : void
asyncResult IAsyncResult
Результат void
Пример #1
0
 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();
 }
Пример #2
0
 /// <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();
 }
Пример #3
0
 public void EndWriteThrowsForNullAsyncResult()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite))
     {
         Assert.Throws<ArgumentNullException>("asyncResult", () => fs.EndWrite(null));
     }
 }
Пример #4
0
        public override void EndWrite(IAsyncResult asyncResult)
        {
            if (_m_disposed)
            {
                throw ADP.ObjectDisposed(this);
            }

            _m_fs.EndWrite(asyncResult);
        }
Пример #5
0
 void OnWriteDone(IAsyncResult ar)
 {
     Enqueue(delegate {
         if (stream != null)
         {
             stream.EndWrite(ar);
             HandleWrite();
         }
     });
 }
Пример #6
0
 void OnWriteDone(IAsyncResult ar)
 {
     Context.Enqueue(delegate {
         if (stream != null)
         {
             ResetWriteTimeout();
             stream.EndWrite(ar);
             HandleWrite();
         }
     });
 }
Пример #7
0
    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);
        }
    }
Пример #8
0
 static public int EndWrite(IntPtr l)
 {
     try {
         System.IO.FileStream self = (System.IO.FileStream)checkSelf(l);
         System.IAsyncResult  a1;
         checkType(l, 2, out a1);
         self.EndWrite(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #9
0
        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);
        }
Пример #11
0
 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);
 }
Пример #12
0
        private static void SampleAsyncMethods()
        {
            IAsyncResult asyncResult;

            /***** SQL Connection *****/
            // NOTE: "Async=true" setting required for asynchronous operations.
            using (SqlConnection connection = new SqlConnection(@"Async=true;Server=SERVER;Database=DATABASE;Integrated Security=true"))
            {
                connection.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT UserId, Name, LastLogIn FROM Users WHERE Email = '*****@*****.**'", connection))
                {
                    asyncResult = cmd.BeginExecuteReader();
                    // ... query executes asynchronously in background ...
                    using (IDataReader reader = cmd.EndExecuteReader(asyncResult))
                    {
                        // WARNING: The DbAsyncResult object returned by BeginExecuteReader always creates a ManualResetEvent, but
                        // never closes it; after calling EndExecuteReader, the AsyncWaitHandle property is still valid, so we close it explicitly.
                        asyncResult.AsyncWaitHandle.Close();

                        while (reader.Read())
                        {
                            // do stuff
                        }
                    }
                }

                using (SqlCommand cmd = new SqlCommand("UPDATE Users SET LastLogIn = GETUTCDATE() WHERE UserId = 1", connection))
                {
                    asyncResult = cmd.BeginExecuteNonQuery();
                    // ... query executes asynchronously in background ...
                    int rowsAffected = cmd.EndExecuteNonQuery(asyncResult);

                    // WARNING: The DbAsyncResult object returned by BeginExecuteNonQuery always creates a ManualResetEvent, but
                    // never closes it; after calling EndExecuteReader, the AsyncWaitHandle property is still valid, so we close it explicitly.
                    asyncResult.AsyncWaitHandle.Close();
                }
            }

            /***** File Operations *****/
            // NOTE: FileOptions.Asynchronous flag required for asynchronous operations.
            using (Stream stream = new FileStream(@"C:\Temp\test.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096,
                FileOptions.Asynchronous))
            {
                byte[] buffer = new byte[65536];
                asyncResult = stream.BeginRead(buffer, 0, buffer.Length, null, null);
                // ... disk read executes asynchronously in background ...
                int bytesRead = stream.EndRead(asyncResult);
            }

            /***** HTTP Operation *****/
            // WARNING: DNS operations are synchronous, and will block!
            WebRequest request = WebRequest.Create(new Uri(@"http://www.example.com/sample/page"));
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            asyncResult = request.BeginGetRequestStream(null, null);
            // ... connection to server opened in background ...
            using (Stream stream = request.EndGetRequestStream(asyncResult))
            {
                byte[] bytes = Encoding.UTF8.GetBytes("Sample request");
                asyncResult = stream.BeginWrite(bytes, 0, bytes.Length, null, null);
                stream.EndWrite(asyncResult);
            }

            // WARNING: WebRequest will swallow any exceptions thrown from the AsyncCallback passed to BeginGetResponse.
            asyncResult = request.BeginGetResponse(null, null);
            // ... web request executes in background ...
            using (WebResponse response = request.EndGetResponse(asyncResult))
            using (Stream stream = response.GetResponseStream())
            {
                // read response from server
                // WARNING: This code should also use asynchronous operations (BeginRead, EndRead); "Using synchronous calls
                //   in asynchronous callback methods can result in severe performance penalties." (MSDN)
            }

            /***** DNS hostname resolution *****/
            // WARNING: Doesn't truly use async I/O, but simply queues the request to a ThreadPool thread.
            asyncResult = Dns.BeginGetHostEntry("www.example.com", null, null);
            // ... DNS lookup executes in background
            IPHostEntry entry = Dns.EndGetHostEntry(asyncResult);

            /***** Other: Sockets, Serial Ports, SslStream *****/
        }
Пример #13
0
 public override void EndWrite(IAsyncResult asyncResult)
 {
     tempStream.EndWrite(asyncResult);
 }
		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));
		}
Пример #15
0
        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("接受到文件"));
                }

            }
        }
Пример #16
0
        public override IEnumerator<CoroutineState> GetEnumerator()
        {
            FileStream fileReader = new FileStream(
                _fileName,
                 FileMode.Open,
                 FileAccess.Read,
                 FileShare.Read,
                 BUFFER_SIZE,
                 true);

            FileStream fileWriter = new FileStream(
                Path.Combine(_destinationFolder, Path.GetFileName(_fileName)),
                FileMode.Create,
                FileAccess.ReadWrite,
                FileShare.Write,
                BUFFER_SIZE,
                true);

            int bytesRead = 0;

            do
            {
                //Read asynchronously
                bool finishedRead = false;
                IAsyncResult readResult = fileReader.BeginRead(_buffer, 0, BUFFER_SIZE,
                    (asyncResult) =>
                    {
                        bytesRead = fileReader.EndRead(asyncResult);
                        finishedRead = true;
                    },
                    null);

                //Wait until the reading is complete
                while (!finishedRead)
                {
                    //Allow other coroutines to run
                    yield return CoroutineState.Running;
                }
                Console.WriteLine("Finished reading chunk for: " + _fileName);

                //Write asynchronously
                bool finishedWriting = false;
                IAsyncResult writeResult = fileWriter.BeginWrite(_buffer, 0, bytesRead,
                    (asyncResult) =>
                    {
                        fileWriter.EndWrite(asyncResult);
                        finishedWriting = true;
                    },
                    null);

                //Wait until write is finished
                while (!finishedWriting)
                {
                    //Let other coroutines run
                    yield return CoroutineState.Running;
                }
                Console.WriteLine("Finished writing chunk for: " + _fileName);

            } while (bytesRead > 0);

            fileReader.Close();
            fileWriter.Close();
        }
Пример #17
0
    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));
    }
Пример #18
0
        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);
                    }
                }
            }
        }
        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);
            }
        }
        /// <summary>
        /// Copies the specified source file to the specified destination file, overwriting if it exists.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="destination">The destination.</param>
        public static void Copy(string source, string destination)
        {
            var bufferLength = 4 * 1024 * 32;
            var readBuffer = new Byte[bufferLength];
            var writeBuffer = new Byte[bufferLength];
            var readSize = -1;

            IAsyncResult writeResult;
            IAsyncResult readResult;

            using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan))
            using (var destinationStream = new FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan))
            {
                destinationStream.SetLength(sourceStream.Length);
                readSize = sourceStream.Read(readBuffer, 0, readBuffer.Length);
                readBuffer = Interlocked.Exchange(ref writeBuffer, readBuffer);

                while (readSize > 0)
                {
                    writeResult = destinationStream.BeginWrite(writeBuffer, 0, readSize, null, null);
                    readResult = sourceStream.BeginRead(readBuffer, 0, readBuffer.Length, null, null);
                    destinationStream.EndWrite(writeResult);
                    readSize = sourceStream.EndRead(readResult);
                    readBuffer = Interlocked.Exchange(ref writeBuffer, readBuffer);
                }

                sourceStream.Close();
                destinationStream.Close();
            }
        }
Пример #21
0
 public void UploadFile(CustomFileInfo currentUploadFile)
 {
     try
     {
         logger.Info("Begin to writer file...");
         if (!Directory.Exists(MediaConfiguration.StoragePath))
         {
             Directory.CreateDirectory(MediaConfiguration.StoragePath);
         }
         var fs = new FileStream(MediaConfiguration.StoragePath + "\\" + currentUploadFile.FileName,
                             FileMode.OpenOrCreate, FileAccess.Write);
         fs.Seek(currentUploadFile.CurrentOffset, SeekOrigin.Begin);
         fs.BeginWrite(
             currentUploadFile.CurrentData, 0,
             currentUploadFile.CurrentLen,
             delegate(IAsyncResult ra)
             {
                 fs.EndWrite(ra);
                 fs.Close();
                 fs.Dispose();
             }, null);
     }
     catch (Exception e)
     {
         logger.Error("Error occurred when writing file, details: {0}.", e);
     }
 }
Пример #22
0
 public void UploadChunk(ChunkInfo chunkInfo)
 {
     try
     {
         var fs = new FileStream(MediaConfiguration.StoragePath
             + "\\" + chunkInfo.StrongChecksum,
             FileMode.OpenOrCreate, FileAccess.Write);
         fs.BeginWrite(
             chunkInfo.Buffer, 0,
             chunkInfo.BufferLength,
             delegate(IAsyncResult ra)
             {
                 try
                 {
                     fs.EndWrite(ra);
                     fs.Close();
                     fs.Dispose();
                     fs = null;
                     MediaIndexOperator.GetIndexDatabaseHelper()
                         .ExecuteNonQuery(new List<ChunkPathMap>
                         {
                             new ChunkPathMap
                             {
                                 ChunkId = chunkInfo.Id,
                                 Path = MediaConfiguration.StoragePath
                             }
                         });
                 }
                 catch (Exception e)
                 {
                     logger.Error("Error occurred when uploading chunk, " +
                                  "details: {0}.", e);
                 }
             }, null);
     }
     catch (Exception e)
     {
         logger.Error("Error occurred when writing file, details: {0}.",
             e);
     }
     finally
     {
         MediaConfiguration.MediaControl.MediaControlProxy
             .CompleteSession(MediaConfiguration.CurrrentMedia.Id);
     }
 }
Пример #23
0
 void OnWriteDone(IAsyncResult ar)
 {
     stream.EndWrite(ar);
     loop.NonBlockInvoke(HandleWrite);
 }