Device I/O FileStream Class Constructors Properties Methods Extension Methods Remarks Detection of Stream Position Changes Applies to See also MemoryStream Class Constructors Properties Methods Remarks Applies to See also Examples Source/Reference
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, and buffer size.
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, buffer size, and synchronous or asynchronous state.
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.
Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state.
Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.
Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.
Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.
Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.
Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.
Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.
Writes a byte to the current position in the file stream.
Extension Methods
Remarks
Use the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the Read, Write, CopyTo, and Flush
methods to perform synchronous operations, or the ReadAsync, WriteAsync, CopyToAsync, and FlushAsync methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream
operation can block the UI thread and make your app appear as if it is not working. FileStream buffers input and output for better performance.
Important
This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.
The IsAsync property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the FileStream class using a constructor that has an isAsync, useAsync, or options parameter. When the property is true, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the IsAsync property does not have to be true to call the
ReadAsync, WriteAsync, or CopyToAsync method. When the IsAsync property is false and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously.
The Seek method supports random access to files. Seek allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the SeekOrigin enumeration.
Note
Disk files always support random access. At the time of construction, the CanSeek property value is set to true or false depending on the underlying file type.If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the CanSeek property value is true. Otherwise, the CanSeek property value is false.
If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.
For directory operations and other file operations, see the File, Directory, and Path classes. The File class is a utility class that has static methods primarily for the creation of FileStream objects based on file paths. The
MemoryStream class creates a stream from a byte array and is similar to the FileStream class.
For a list of common file and directory operations, see Common I/O Tasks.
Detection of Stream Position Changes
When a FileStream object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the FileStream object and the cached data in the buffer could be compromised. The FileStream object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the
FileStream object.
If an unexpected change in the handle position is detected in a call to the Read method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream.
If an unexpected change in the handle position is detected in a call to the Write method, the contents of the buffer are discarded and an IOException exception is thrown.
A FileStream object will not have an exclusive hold on its handle when either the SafeFileHandle property is accessed to expose the handle or the FileStream object is given the SafeFileHandle property in its constructor.
Initializes a new non-resizable instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified.
Initializes a new instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified, and the ability to call GetBuffer() set as specified.
Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.
Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.
Writes the entire contents of this memory stream to another stream.
Remarks
The current position of a stream is the position at which the next read or write operation could take place. The current position can be retrieved or set through the Seek method. When a new instance of MemoryStream is created, the current position is set to zero.
Note
This type implements the IDisposable interface, but does not actually have any resources to dispose. This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.
Memory streams created with an unsigned byte array provide a non-resizable stream of the data. When using a byte array, you can neither append to nor shrink the stream, although you might be able to modify the existing contents depending on the parameters passed into the constructor. Empty memory streams are resizable, and can be written to and read from.
If a MemoryStream object is added to a ResX file or a .resources file, call the GetStream method at runtime to retrieve it.
If a MemoryStream object is serialized to a resource file it will actually be serialized as an UnmanagedMemoryStream. This behavior provides better performance, as well as the ability to get a pointer to the data directly, without having to go through Stream methods.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Sample Page</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script runat="server" >
Sub Page_Load()
Dim xstr As String
Dim xstr1 As String = "abcdefgh"
Dim xstr2 As String = "i"
Dim xbytes As Byte()
Dim xbytes1 As Byte() = System.Text.Encoding.ASCII.GetBytes(xstr1)
Dim xbytes2 As Byte() = System.Text.Encoding.ASCII.GetBytes(xstr2)
Dim xpath As String = "T:\filestream\filestream.txt"
Dim xi As Integer
If System.IO.Directory.Exists("T:\filestream") Then
System.IO.Directory.Delete("T:\filestream", true)
End If
System.IO.Directory.CreateDirectory("T:\filestream")
xstr = "instantiate a filestream of " & xpath & "<br /><br />"
Dim xfstream As New System.IO.FileStream(xpath,System.IO.FileMode.Create)
xstr = xstr & "Given string: " & xstr1 & "<br />"
xstr = xstr & "ASCII encoded bytes: "
For xi = 0 to xbytes1.Length-1
xstr = xstr & xbytes1(xi) & " "
Next
xstr = xstr & "<br />Write the bytes filestream to a file of path '" & xpath & "'.<br />"
xfstream.Write(xbytes1, 0, xbytes1.Length)
xstr = xstr & "<br />Given string: " & xstr2 & "<br />"
xstr = xstr & "ASCII encoded bytes: "
For xi = 0 to xbytes2.Length-1
xstr = xstr & xbytes2(xi) & " "
Next
xstr = xstr & "<br />Write the byte filestream to a file of path '" & xpath & "'.<br />"
xfstream.WriteByte(xbytes2(0))
xfstream.Flush()
xstr = xstr & "<br />Set the filestream position to " & xfstream.seek(0,0) & "<br />"
xstr = xstr & "<br />Read one byte: " & xfstream.ReadByte() & "<br />"
ReDim xbytes(xfstream.Length-2)
xfstream.Read(xbytes,0,xfstream.Length-1)
xstr = xstr & "<br />Read all other bytes: "
For xi = 0 to xbytes.Length-1
xstr = xstr & xbytes(xi) & " "
Next
xfstream.Dispose()
lbl01.Text = xstr
End Sub
</script>
</head>
<body>
<%Response.Write("<p>Results on "& Request.ServerVariables("SERVER_SOFTWARE") & " .net: " & System.Environment.Version.ToString & " " & ScriptEngine & " Version " & ScriptEngineMajorVersion & "." & ScriptEngineMinorVersion & "</p>")%>
<% Response.Write ("<h1>This is a Sample Page of FileStream Class</h1>") %>
<p>
<%-- Set on Page_Load --%>
<asp:Label id="lbl01" runat="server" />
</p>
</body>
</html>