System.IO.FileStream
Class System.IO.FileStream
Exposes a Stream
that accesses a backing store such as a file, recursively. The FileStream
object is the concrete implementation of the abstract Stream
class.
Constructors
public FileStream(string path, FileMode mode)
Initializes a new instance of the FileStream
class with the specified path and creation mode.
public FileStream(string path, FileMode mode, FileAccess access)
Initializes a new instance of the FileStream
class with the specified path, creation mode, and access.
public FileStream(string path, FileMode mode, FileAccess access, int bufferSize)
Initializes a new instance of the FileStream
class with the specified path, creation mode, access, and buffer size.
Properties
public override bool CanRead { get; }
Gets a value indicating whether the current stream supports reading.
public override bool CanSeek { get; }
Gets a value indicating whether the current stream supports seeking.
public override bool CanTimeout { get; }
Gets a value indicating whether the current stream supports setting this Timeout
property.
public override long Length { get; }
Gets the length in bytes of the stream.
public override long Position { get; set; }
Gets or sets the current position within the stream.
Methods
public override void Close()
Closes the current stream and releases any resources (such as file handles) associated with the current stream.
protected override void Dispose(bool disposing)
Releases the unmanaged resources that are used by the object and, optionally, releases the managed resources.
public override int Read(byte[] buffer, int offset, int count)
Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
public override void Write(byte[] buffer, int offset, int count)
Writes a sequence of bytes to the current stream and advances the position within the stream by the number of bytes written.
Example
The following code example demonstrates how to use the FileStream
class to write to and read from a file.
using System;
using System.IO;
public class Example
{
public static void Main()
{
// Create a FileStream object for writing.
using (FileStream fs = new FileStream("example.txt", FileMode.Create))
{
byte[] data = new byte[1024];
for (int i = 0; i < data.Length; ++i)
{
data[i] = (byte)i;
}
// Write data to the file.
fs.Write(data, 0, data.Length);
Console.WriteLine("Wrote {0} bytes to example.txt.", data.Length);
}
// Create a FileStream object for reading.
using (FileStream fs = new FileStream("example.txt", FileMode.Open))
{
byte[] data = new byte[1024];
int bytesRead = fs.Read(data, 0, data.Length);
Console.WriteLine("Read {0} bytes from example.txt.", bytesRead);
// Verify the data.
bool mismatch = false;
for (int i = 0; i < bytesRead; ++i)
{
if (data[i] != (byte)i)
{
mismatch = true;
break;
}
}
if (mismatch)
{
Console.WriteLine("Data mismatch detected.");
}
else
{
Console.WriteLine("Data read matches data written.");
}
}
}
}