C# FileStream BeginWrite

In this chapter you will learn:

  1. Get to know FileStream.BeginWrite
  2. Syntax for FileStream.BeginWrite
  3. Parameter for FileStream.BeginWrite
  4. Returns for FileStream.BeginWrite
  5. Example - FileStream.BeginWrite

Description

FileStream BeginWrite Begins an asynchronous write operation. (Consider using WriteAsync instead; see the Remarks section.)

Syntax

FileStream.BeginWrite has the following syntax.


[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public override IAsyncResult BeginWrite(
  byte[] array,//  ww w.  j a va  2  s . co  m
  int offset,
  int numBytes,
  AsyncCallback userCallback,
  Object stateObject
)

Parameters

FileStream.BeginWrite has the following parameters.

  • array - The buffer containing data to write to the current stream.
  • offset - The zero-based byte offset in array at which to begin copying bytes to the current stream.
  • numBytes - The maximum number of bytes to write.
  • userCallback - The method to be called when the asynchronous write operation is completed.
  • stateObject - A user-provided object that distinguishes this particular asynchronous write request from other requests.

Returns

FileStream.BeginWrite method returns An object that references the asynchronous write.

Example


/*w w  w  .  j a v  a 2  s.  c om*/
using System;
public class MainClass{
  public static void Main(String[] argv){  
    System.Console.WriteLine();
  }
  static void Main()
  {
        ManualResetEvent manualEvent = new ManualResetEvent(false);
        byte[] writeArray = new byte[100000];
        new Random().NextBytes(writeArray);
    
        FileStream fStream = 
            new FileStream("Test.dat", FileMode.Create, 
            FileAccess.ReadWrite, FileShare.None, 4096, true);
    
        IAsyncResult asyncResult = fStream.BeginWrite(
            writeArray, 0, writeArray.Length, 
            new AsyncCallback(EndWriteCallback), 
            new State(fStream, writeArray, manualEvent));
    
        manualEvent.WaitOne(5000, false);
  }  
}
    

Next chapter...

What you will learn in the next chapter:

  1. Get to know FileStream.CopyTo(Stream)
  2. Syntax for FileStream.CopyTo(Stream)
  3. Parameter for FileStream.CopyTo(Stream)
  4. Returns for FileStream.CopyTo(Stream)
  5. Example - FileStream.CopyTo(Stream)