FileStream Class
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.
public ref class FileStream : System::IO::Stream
public class FileStream : System.IO.Stream
[System.Runtime.InteropServices.ComVisible(true)]
public class FileStream : System.IO.Stream
type FileStream = class
inherit Stream
[<System.Runtime.InteropServices.ComVisible(true)>]
type FileStream = class
inherit Stream
Public Class FileStream
Inherits Stream
- Inheritance
- Inheritance
- Derived
- Attributes
The following example demonstrates some of the FileStream constructors.
using namespace System;
using namespace System::IO;
using namespace System::Text;
void AddText( FileStream^ fs, String^ value )
{
array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( value );
fs->Write( info, 0, info->Length );
}
int main()
{
String^ path = "c:\\temp\\MyTest.txt";
// Delete the file if it exists.
if ( File::Exists( path ) )
{
File::Delete( path );
}
//Create the file.
{
FileStream^ fs = File::Create( path );
try
{
AddText( fs, "This is some text" );
AddText( fs, "This is some more text," );
AddText( fs, "\r\nand this is on a new line" );
AddText( fs, "\r\n\r\nThe following is a subset of characters:\r\n" );
for ( int i = 1; i < 120; i++ )
{
AddText( fs, Convert::ToChar( i ).ToString() );
//Split the output at every 10th character.
if ( Math::IEEERemainder( Convert::ToDouble( i ), 10 ) == 0 )
{
AddText( fs, "\r\n" );
}
}
}
finally
{
if ( fs )
delete (IDisposable^)fs;
}
}
//Open the stream and read it back.
{
FileStream^ fs = File::OpenRead( path );
try
{
array<Byte>^b = gcnew array<Byte>(1024);
UTF8Encoding^ temp = gcnew UTF8Encoding( true );
while ( fs->Read( b, 0, b->Length ) > 0 )
{
Console::WriteLine( temp->GetString( b ) );
}
}
finally
{
if ( fs )
delete (IDisposable^)fs;
}
}
}
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
//Create the file.
using (FileStream fs = File.Create(path))
{
AddText(fs, "This is some text");
AddText(fs, "This is some more text,");
AddText(fs, "\r\nand this is on a new line");
AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");
for (int i=1;i < 120;i++)
{
AddText(fs, Convert.ToChar(i).ToString());
}
}
//Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
int readLen;
while ((readLen = fs.Read(b,0,b.Length)) > 0)
{
Console.WriteLine(temp.GetString(b,0,readLen));
}
}
}
private static void AddText(FileStream fs, string value)
{
byte[] info = new UTF8Encoding(true).GetBytes(value);
fs.Write(info, 0, info.Length);
}
}
open System
open System.IO
open System.Text
let addText (fs:FileStream) (value: string) =
let info = UTF8Encoding(true).GetBytes value
fs.Write(info, 0, info.Length);
let path = @"c:\temp\MyTest.txt"
// Delete the file if it exists.
if File.Exists path then
File.Delete path
//Create the file.
do
use fs = File.Create path
addText fs "This is some text"
addText fs "This is some more text,"
addText fs "\r\nand this is on a new line"
addText fs "\r\n\r\nThe following is a subset of characters:\r\n"
for i = 1 to 119 do
Convert.ToChar i
|> string
|> addText fs
do
//Open the stream and read it back.
use fs = File.OpenRead path
let b = Array.zeroCreate 1024
let temp = UTF8Encoding true
let mutable readLen = fs.Read(b,0,b.Length);
while readLen> 0 do
printfn $"{temp.GetString(b,0,readLen)}"
readLen <- fs.Read(b,0,b.Length)
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
' Delete the file if it exists.
If File.Exists(path) Then
File.Delete(path)
End If
'Create the file.
Dim fs As FileStream = File.Create(path)
AddText(fs, "This is some text")
AddText(fs, "This is some more text,")
AddText(fs, Environment.NewLine & "and this is on a new line")
AddText(fs, Environment.NewLine & Environment.NewLine)
AddText(fs, "The following is a subset of characters:" & Environment.NewLine)
Dim i As Integer
For i = 1 To 120
AddText(fs, Convert.ToChar(i).ToString())
Next
fs.Close()
'Open the stream and read it back.
fs = File.OpenRead(path)
Dim b(1023) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While fs.Read(b, 0, b.Length) > 0
Console.WriteLine(temp.GetString(b))
Loop
fs.Close()
End Sub
Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)
Dim info As Byte() = New UTF8Encoding(True).GetBytes(value)
fs.Write(info, 0, info.Length)
End Sub
End Class
The following example shows how to write to a file asynchronously. This code runs in a WPF app that has a TextBlock named UserInput and a button hooked up to a Click event handler that is named Button_Click. The file path needs to be changed to a file that exists on the computer.
using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.IO;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
UnicodeEncoding uniencoding = new UnicodeEncoding();
string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";
byte[] result = uniencoding.GetBytes(UserInput.Text);
using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))
{
SourceStream.Seek(0, SeekOrigin.End);
await SourceStream.WriteAsync(result, 0, result.Length);
}
}
}
}
Imports System.IO
Imports System.Text
Class MainWindow
Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim uniencoding As UnicodeEncoding = New UnicodeEncoding()
Dim filename As String = "c:\Users\exampleuser\Documents\userinputlog.txt"
Dim result As Byte() = uniencoding.GetBytes(UserInput.Text)
Using SourceStream As FileStream = File.Open(filename, FileMode.OpenOrCreate)
SourceStream.Seek(0, SeekOrigin.End)
Await SourceStream.WriteAsync(result, 0, result.Length)
End Using
End Sub
End Class
For more information about this API, see Supplemental API remarks for FileStream.
File |
Obsolete.
Obsolete.
Obsolete.
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, |
File |
Obsolete.
Obsolete.
Obsolete.
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, |
File |
Obsolete.
Obsolete.
Obsolete.
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and |
File |
Obsolete.
Obsolete.
Obsolete.
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission. |
File |
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. |
File |
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, and buffer size. |
File |
Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission. |
File |
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. |
File |
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. |
File |
Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size. |
File |
Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission. |
File |
Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission. |
File |
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. |
File |
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. |
File |
Initializes a new instance of the FileStream class with the specified path and creation mode. |
File |
Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, additional file options, preallocation size, and the access other FileStreams can have to the same file. |
Can |
Gets a value that indicates whether the current stream supports reading. |
Can |
Gets a value that indicates whether the current stream supports seeking. |
Can |
Gets a value that determines whether the current stream can time out. (Inherited from Stream) |
Can |
Gets a value that indicates whether the current stream supports writing. |
Handle |
Obsolete.
Obsolete.
Obsolete.
Gets the operating system file handle for the file that the current |
Is |
Gets a value that indicates whether the |
Length |
Gets the length in bytes of the stream. |
Name |
Gets the absolute path of the file opened in the |
Position |
Gets or sets the current position of this stream. |
Read |
Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out. (Inherited from Stream) |
Safe |
Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates. |
Write |
Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out. (Inherited from Stream) |
Begin |
Begins an asynchronous read operation. Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead. |
Begin |
Begins an asynchronous read operation. (Consider using ReadAsync(Byte[], Int32, Int32) instead.) (Inherited from Stream) |
Begin |
Begins an asynchronous write operation. Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead. |
Begin |
Begins an asynchronous write operation. (Consider using WriteAsync(Byte[], Int32, Int32) instead.) (Inherited from Stream) |
Close() |
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. |
Close() |
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed. (Inherited from Stream) |
Copy |
Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. |
Copy |
Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Asynchronously reads the bytes from the current file stream and writes them to another stream, using a specified buffer size and cancellation token. |
Copy |
Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Copy |
Asynchronously reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. (Inherited from Stream) |
Create |
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject) |
Create |
Obsolete.
Obsolete.
Obsolete.
Allocates a WaitHandle object. (Inherited from Stream) |
Dispose() |
Releases all resources used by the Stream. (Inherited from Stream) |
Dispose(Boolean) |
Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. |
Dispose |
Asynchronously releases the unmanaged resources used by the FileStream. |
Dispose |
Asynchronously releases the unmanaged resources used by the Stream. (Inherited from Stream) |
End |
Waits for the pending asynchronous read operation to complete. (Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.) |
End |
Waits for the pending asynchronous read to complete. (Consider using ReadAsync(Byte[], Int32, Int32) instead.) (Inherited from Stream) |
End |
Ends an asynchronous write operation and blocks until the I/O operation is complete. (Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.) |
End |
Ends an asynchronous write operation. (Consider using WriteAsync(Byte[], Int32, Int32) instead.) (Inherited from Stream) |
Equals(Object) |
Determines whether the specified object is equal to the current object. (Inherited from Object) |
Finalize() |
Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the |
Flush() |
Clears buffers for this stream and causes any buffered data to be written to the file. |
Flush(Boolean) |
Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers. |
Flush |
Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device. (Inherited from Stream) |
Flush |
Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. |
Flush |
Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests. (Inherited from Stream) |
Get |
Gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object. |
Get |
Serves as the default hash function. (Inherited from Object) |
Get |
Obsolete.
Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject) |
Get |
Gets the Type of the current instance. (Inherited from Object) |
Initialize |
Obsolete.
Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject) |
Lock(Int64, Int64) |
Prevents other processes from reading from or writing to the FileStream. |
Memberwise |
Creates a shallow copy of the current Object. (Inherited from Object) |
Memberwise |
Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject) |
Object |
Obsolete.
Provides support for a Contract. (Inherited from Stream) |
Read(Byte[], Int32, Int32) |
Reads a block of bytes from the stream and writes the data in a given buffer. |
Read(Span<Byte>) |
Reads a sequence of bytes from the current file stream and advances the position within the file stream by the number of bytes read. |
Read(Span<Byte>) |
When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited from Stream) |
Read |
Asynchronously reads a sequence of bytes from the current file stream and writes them to a byte array beginning at a specified offset, advances the position within the file stream by the number of bytes read, and monitors cancellation requests. |
Read |
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. (Inherited from Stream) |
Read |
Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited from Stream) |
Read |
Asynchronously reads a sequence of bytes from the current file stream and writes them to a memory region, advances the position within the file stream by the number of bytes read, and monitors cancellation requests. |
Read |
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. (Inherited from Stream) |
Read |
Reads at least a minimum number of bytes from the current stream and advances the position within the stream by the number of bytes read. (Inherited from Stream) |
Read |
Asynchronously reads at least a minimum number of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. (Inherited from Stream) |
Read |
Reads a byte from the file and advances the read position one byte. |
Read |
Reads |
Read |
Reads bytes from the current stream and advances the position within the stream until the |
Read |
Asynchronously reads |
Read |
Asynchronously reads bytes from the current stream, advances the position within the stream until the |
Seek(Int64, Seek |
Sets the current position of this stream to the given value. |
Set |
Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object. |
Set |
Sets the length of this stream to the given value. |
To |
Returns a string that represents the current object. (Inherited from Object) |
Unlock(Int64, Int64) |
Allows access by other processes to all or part of a file that was previously locked. |
Write(Byte[], Int32, Int32) |
Writes a block of bytes to the file stream. |
Write(Read |
Writes a sequence of bytes from a read-only span to the current file stream and advances the current position within this file stream by the number of bytes written. |
Write(Read |
When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Inherited from Stream) |
Write |
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. |
Write |
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. (Inherited from Stream) |
Write |
Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. (Inherited from Stream) |
Write |
Asynchronously writes a sequence of bytes from a memory region to the current file stream, advances the current position within this file stream by the number of bytes written, and monitors cancellation requests. |
Write |
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. (Inherited from Stream) |
Write |
Writes a byte to the current position in the file stream. |
IDisposable. |
Releases all resources used by the Stream. (Inherited from Stream) |
Get |
Returns the security information of a file. |
Set |
Changes the security attributes of an existing file. |
Copy |
Asynchronously reads the bytes from the Stream and writes them to the specified PipeWriter, using a cancellation token. |
As |
Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime. |
As |
Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime. |
As |
Converts the specified stream to a random access stream. |
Configure |
Configures how awaits on the tasks returned from an async disposable will be performed. |
Product | Versions |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.3, 1.4, 1.6, 2.0, 2.1 |
UWP | 10.0 |
.NET feedback
.NET is an open source project. Select a link to provide feedback: