Export (0) Print
Expand All

FileStream.BeginWrite Method

Begins an asynchronous write.

[Visual Basic]
Overrides Public Function BeginWrite( _
   ByVal array() As Byte, _
   ByVal offset As Integer, _
   ByVal numBytes As Integer, _
   ByVal userCallback As AsyncCallback, _
   ByVal stateObject As Object _
) As IAsyncResult
[C#]
public override IAsyncResult BeginWrite(
 byte[] array,
 int offset,
 int numBytes,
 AsyncCallback userCallback,
 object stateObject
);
[C++]
public: IAsyncResult* BeginWrite(
 unsigned char array __gc[],
 int offset,
 int numBytes,
 AsyncCallback* userCallback,
 Object* stateObject
);
[JScript]
public override function BeginWrite(
   array : Byte[],
 offset : int,
 numBytes : int,
 userCallback : AsyncCallback,
 stateObject : Object
) : IAsyncResult;

Parameters

array
The buffer to write data to.
offset
The zero based byte offset in array at which to begin writing.
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.

Return Value

An IAsyncResult that references the asynchronous write.

Exceptions

Exception Type Condition
ArgumentException array length minus offset is less than numBytes.
ArgumentNullException array is a null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException offset or numBytes is negative.
NotSupportedException The stream does not support writing.
ObjectDisposedException The stream is closed.
IOException An I/O error occurs.

Remarks

This method overrides BeginWrite.

FileStream provides two different modes of operation: synchronous I/O and asynchronous I/O. While either can be used, the underlying operating system resources might allow access in only one of these modes. By default, FileStream opens the operating system handle synchronously. In Windows, this slows down asynchronous methods. If asynchronous methods are used, use the FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean) constructor.

If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from BeginWrite. Errors that occur during an asynchronous write request, such as a disk failure during the IO request, occur on the threadpool thread and become visible upon a call to EndWrite.

Note   On Windows, all I/O operations smaller than 64 KB will complete synchronously for better performance. Asynchronous I/O might hinder performance for buffer sizes smaller than 64 KB.

EndWrite must be called with this IAsyncResult to find out how many bytes were read.

Multiple simultaneous asynchronous requests render the request completion order uncertain.

The following table lists examples of other typical or related I/O tasks.

To do this... See the example in this topic...
Create a text file. Writing Text to a File
Write to a text file. Writing Text to a File
Read from a text file. Reading Text from a File
Append text to a file. Opening and Appending to a Log File

File.AppendText

FileInfo.AppendText

Rename or move a file. File.Move

FileInfo.MoveTo

Copy a file. File.Copy

FileInfo.CopyTo

Get the size of a file. FileInfo.Length
Get the attributes of a file. File.GetAttributes
Set the attributes of a file. File.SetAttributes
Determine if a file exists. File.Exists
Read from a binary file. Reading and Writing to a Newly Created Data File
Write to a binary file. Reading and Writing to a Newly Created Data File
Create a directory. Directory.CreateDirectory

Directory.CreateDirectory

Example

[Visual Basic, C#, C++] This code example is part of a larger example provided for System.IO.FileStream.FileStream4.

[Visual Basic] 
Shared Sub Main()

    ' Create a synchronization object that gets 
    ' signaled when verification is complete.
    Dim manualEvent As New ManualResetEvent(False)

    ' Create random data to write to the file.
    Dim writeArray(100000) As Byte
    Dim randomGenerator As New Random()
    randomGenerator.NextBytes(writeArray)

    Dim fStream As New FileStream("Test#@@#.dat", _
        FileMode.Create, FileAccess.ReadWrite, _
        FileShare.None, 4096, True)

    ' Check that the FileStream was opened asynchronously.
    If fStream.IsAsync = True
        Console.WriteLine("fStream was opened asynchronously.")
    Else
        Console.WriteLine("fStream was not opened asynchronously.")
    End If

    ' Asynchronously write to the file.
    Dim asyncResult As IAsyncResult = fStream.BeginWrite( _
        writeArray, 0, writeArray.Length, _
        AddressOf EndWriteCallback , _
        New State(fStream, writeArray, manualEvent))

    ' Concurrently do other work and then wait
    ' for the data to be written and verified.
    manualEvent.WaitOne(5000, False)
End Sub

[C#] 
static void Main()
{
    // Create a synchronization object that gets 
    // signaled when verification is complete.
    ManualResetEvent manualEvent = new ManualResetEvent(false);

    // Create random data to write to the file.
    byte[] writeArray = new byte[100000];
    new Random().NextBytes(writeArray);

    FileStream fStream = 
        new FileStream("Test#@@#.dat", FileMode.Create, 
        FileAccess.ReadWrite, FileShare.None, 4096, true);

    // Check that the FileStream was opened asynchronously.
    Console.WriteLine("fStream was {0}opened asynchronously.",
        fStream.IsAsync ? "" : "not ");

    // Asynchronously write to the file.
    IAsyncResult asyncResult = fStream.BeginWrite(
        writeArray, 0, writeArray.Length, 
        new AsyncCallback(EndWriteCallback), 
        new State(fStream, writeArray, manualEvent));

    // Concurrently do other work and then wait 
    // for the data to be written and verified.
    manualEvent.WaitOne(5000, false);
}

[C++] 
void main()
{
    // Create a synchronization object that gets 
    // signaled when verification is complete.
    ManualResetEvent* manualEvent = new ManualResetEvent(false);

    // Create the data to write to the file.
    Byte writeArray __gc[] = new Byte __gc [100000];
    (new Random())->NextBytes(writeArray);

    FileStream* fStream = 
        new FileStream("Test#@@#.dat", FileMode::Create, 
        FileAccess::ReadWrite, FileShare::None, 4096, true);

    // Check that the FileStream was opened asynchronously.
    Console::WriteLine(S"fStream was {0}opened asynchronously.",
        fStream->IsAsync ? S"" : S"not ");

    // Asynchronously write to the file.
    IAsyncResult* asyncResult = fStream->BeginWrite(
        writeArray, 0, writeArray->Length, 
        new AsyncCallback(0, &FStream::EndWriteCallback), 
        new State(fStream, writeArray, manualEvent));

    // Concurrently do other work and then wait 
    // for the data to be written and verified.
    manualEvent->WaitOne(5000, false);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

FileStream Class | FileStream Members | System.IO Namespace | Working with I/O | Reading Text from a File | Writing Text to a File | Asynchronous File I/O

Show:
© 2014 Microsoft