What FileStream property indicates whether the FileStream supports reading?
FileStream is used for reading and writing files on a file system, as well as other file-related operating system handles such as pipes, standard input, standard output. FileStream buffers input and output for better performance. The FileStream class can open a file in one of two modes, either synchronously or asynchronously, with significant performance consequences for the synchronous methods (System.IO.FileStream.Read(System.Byte[],System.Int32,System.Int32) and System.IO.FileStream.Write(System.Byte[],System.Int32,System.Int32)) and the asynchronous methods (System.IO.FileStream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) and System.IO.FileStream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) ). Both sets of methods will work in either mode; however, the mode will affect the performance of these methods. FileStream defaults to opening files synchronously, but provides a constructor to open files asynchronously. Show When accessing files, a security check is performed when the file is created or opened. The security check is typically not done again unless the file is closed and reopened. [Note: Checking permissions when the file is first accessed minimizes the impact of the security check on application performance (since opening a file happens once, while reading and writing can happen multiple times).] Note that if an opened file is passed to an untrusted caller, the security system can, but is not required to prevent the caller from accessing the file. FileStream objects support random access to files using the System.IO.FileStream.Seek(System.Int64,System.IO.SeekOrigin) method, and the System.IO.Stream.CanSeek properties of FileStream instances encapsulating files are set to true . The System.IO.FileStream.Seek(System.Int64,System.IO.SeekOrigin) method 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 values of the SeekOrigin enumeration. If a FileStream encapsulates a device that does not support seeking, its System.IO.FileStream.CanSeek property is false . [Note: For additional information, see System.IO.Stream.CanSeek.] [Note: The File class provides methods for the creation of FileStream objects based on file paths. The MemoryStream class creates a stream from a byte array and functions similarly to a FileStream.] The following example demonstrates the use of a FileStream object.using System; using System.IO; class Directory { public static void Main(String[] args) { FileStream fs = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Write); StreamWriter w = new StreamWriter(fs); w.BaseStream.Seek(0, SeekOrigin.End); // Set the file pointer to the end. Log ("Test1", w); Log ("Test2", w); w.Close(); // Close the writer and underlying file. fs = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Read); StreamReader r = new StreamReader(fs); r.BaseStream.Seek(0, SeekOrigin.Begin); DumpLog (r); } public static void Log (String logMessage, StreamWriter w) { w.Write("Log Entry : "); w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); w.WriteLine(":"); w.WriteLine(":{0}", logMessage); w.WriteLine ("-------------------------------"); w.Flush(); } public static void DumpLog (StreamReader r) { while (r.Peek() > -1) { // While not at the end of the file, write to standard output. Console.WriteLine(r.ReadLine()); } r.Close(); } } Some example output is Log Entry : 9:26:21 AM Friday, July 06, 2001 : :Test1 ------------------------------- Log Entry : 9:26:21 AM Friday, July 06, 2001 : :Test2 ------------------------------- Assembly: Mscorlib.dllNamespace: System.IO Summary Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.C# Syntax: public class FileStream : Stream RemarksFileStream is useful for reading and writing files on a file system, as well as other file-related operating system handles (including pipes, standard input, standard output, and so on).FileStream buffers input and output for better performance.The FileStream class can open a file in one of two modes, either synchronously or asynchronously, with significant performance consequences for the synchronous methods ( FileStream.Read and FileStream.Write) and the asynchronous methods ( FileStream.BeginRead and FileStream.BeginWrite). Both sets of methods will work in either mode; however, the mode will affect the performance of these methods.FileStream defaults to opening files synchronously, but provides a constructor to open files asynchronously. For file and directory operations, see the File, Directory, and Path classes. The File class is a utility class with static methods primarily for the creation of FileStream objects based on file paths and the standard input, standard output, and standard error devices. The MemoryStream class creates a stream from a byte array and functions similarly to a FileStream. If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined. ExampleFileStream objects support random access to files using the FileStream.Seek method. The Seek method 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 properties of the SeekOrigin class.Note Disk files always support random access. At the time of construction, the FileStream.CanSeek property is set to true or false depending on the underlying file type. Specifically, if the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the CanSeek property is true. Otherwise, the CanSeek property is false. In the following example, a file is opened, or created if it does not already exist, and information is appended to the end of the file. The contents of the file are then written to standard output for display. See also: System.IO Namespace | File | FileAccess | FileMode | FileShareSystem.IO.FileStream Member List:Public�Constructors
Hierarchy:
System.IO.FileStream Member DetailsOverloaded ctor #1Summary Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.C# Syntax:Parameters:handle access
FileShare.Read is the default for those FileStream constructors without a FileShare parameter. .NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to topOverloaded ctor #2Summary Initializes a new instance of the FileStream class with the specified path and creation mode.C# Syntax:Parameters: path mode
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, in C#, C++, or JScript code, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt. The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed). The buffer size is set to the default size of 8192 bytes (8 KB). Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek. FileShare.Read is the default for those FileStream constructors without a FileShare parameter. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.See also:Path.InvalidPathChars Return to topOverloaded ctor #3Summary Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.C# Syntax:Parameters: handle access ownsHandle
FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call FileStream.Flush before using the handle, and avoid calling methods other than Close after you are done using the handle. FileShare.Read is the default for those FileStream constructors without a FileShare parameter. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to topOverloaded ctor #4Summary Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.C# Syntax:Parameters: path mode access
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt. The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed). The buffer size is set to the default size of 8192 bytes (8 KB). Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek. FileShare.Read is the default for those FileStream constructors without a FileShare parameter. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to topOverloaded ctor #5Summary 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.C# Syntax:Parameters: handle access ownsHandle bufferSize
FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call FileStream.Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor. FileShare.Read is the default for those FileStream constructors without a FileShare parameter. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to topOverloaded ctor #6Summary Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.C# Syntax:Parameters: path mode access share
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt. The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed). The buffer size is set to the default size of 8192 bytes (8 KB). Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to topOverloaded ctor #7Summary 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.C# Syntax:Parameters: handle access ownsHandle bufferSize isAsync
FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call FileStream.Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor. FileShare.Read is the default for those FileStream constructors without a FileShare parameter. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: SecurityPermission for access to unmanaged code. Associated enumeration: SecurityPermissionFlag.UnmanagedCode.Return to topOverloaded ctor #8Summary Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.C# Syntax:Parameters: path mode access share bufferSize
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt. Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.Return to topOverloaded ctor #9Summary 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.C# Syntax:Parameters: path mode access share bufferSize useAsync
If path contains invalid characters or lacks necessary characters, the code will not compile. For example, you cannot specify "c:\\Dir\myfile.txt" as the path string, because it is missing an escape character in front of the backslash between Dir and myfile.txt. Note path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. Stream.CanSeek is true for all FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the FileStream.CanSeek property on the resulting FileStream is false. For additional information, see Stream.CanSeek. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters may not be interpretable, and could cause an exception to be thrown..NET Framework Security: FileIOPermission for reading, writing, and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Write, and FileIOPermissionAccess.Append.See also:File Return to topOverridden Property: CanRead (read-only) Summary Gets a value indicating whether the current stream supports reading.C# Syntax: public override bool�CanRead {get;} Remarks If a class derived from Stream does not support reading, calls to the FileStream.Read, FileStream.ReadByte, FileStream.BeginRead, and FileStream.EndRead methods throw a NotSupportedException.If the stream is closed, this property returns false. Example The following is an example of using the CanRead property. using System; using System.IO; class TestRW { public static void Main(String[] args) { FileStream fs = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.Read); if (fs.CanRead && fs.CanWrite) { Console.WriteLine("MyFile.txt can be both written to and read from."); } else if (fs.CanRead) { Console.WriteLine("MyFile.txt is not writable."); } } } //This code outputs "MyFile.txt is not writable." //To get the output message "MyFile.txt can be both written to and read from.", //change the FileAccess parameter to ReadWrite in the FileStream constructor.Return to topOverridden Property: CanSeek (read-only) Summary Gets a value indicating whether the current stream supports seeking.C# Syntax: public override bool�CanSeek {get;} Remarks If a class derived from Stream does not support seeking, calls to FileStream.Length, FileStream.SetLength, FileStream.Position, and FileStream.Seek throw a NotSupportedException.If the stream is closed, this property returns false. Return to topOverridden Property: CanWrite (read-only) Summary Gets a value indicating whether the current stream supports writing.C# Syntax: public override bool�CanWrite {get;} Remarks If a class derived from Stream does not support writing, a call to FileStream.SetLength, FileStream.Write, FileStream.BeginWrite, FileStream.EndWrite, or FileStream.WriteByte throws a NotSupportedException.If the stream is closed, this property returns false. Example The following is an example using the CanWrite property. using System; using System.IO; class TestRW { public static void Main(String[] args) { FileStream fs = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.Write); if (fs.CanRead && fs.CanWrite) { Console.WriteLine("MyFile.txt can be both written to and read from."); } else if (fs.CanWrite) { Console.WriteLine("MyFile.txt is writable."); } } } //This code outputs "MyFile.txt is writable." //To get the output message "MyFile.txt can be both written to and read from.", //change the FileAccess parameter to ReadWrite in the FileStream constructor.Return to topProperty: Handle (read-only) Summary Gets the operating system file handle for the file that the current FileStream object encapsulates.C# Syntax: public virtual IntPtr�Handle {get;} Exceptions
The operating system handle might have been opened synchronously or asynchronously, depending on which FileStream constructor was called. Use the FileStream.IsAsync property to discover whether this handle was opened asynchronously. In Win32, this means the handle was opened for overlapped IO, and it requires different parameters to ReadFile and WriteFile. Data corruption might occur if a FileStream is created, its handle is passed, some operation moves the handle's file pointer, and then the FileStream is used again. Multiple threads cannot safely write to the same file simultaneously, and FileStream buffering code assumes that it exclusively controls the handle.FileStream might throw an IOException if FileStream detects that some other process has moved the file pointer. To avoid this, do not write any data into a portion of the file that FileStream might have buffered, and restore the file pointer to the location it had when methods were last called on FileStream..NET Framework Security: SecurityPermission for calling unmanaged code, such as calling native code with PInvoke or COM integration. Associated enumeration: SecurityPermissionFlag.UnmanagedCode.Return to topProperty: IsAsync (read-only) Summary Gets a value indicating whether the FileStream was opened asynchronously or synchronously.C# Syntax: public virtual bool�IsAsync {get;} Remarks The IsAsync property detects whether the FileStream handle was opened asynchronously, enabling your code to use the FileStream.Handle property correctly. In Win32, IsAsync being true means the handle was opened for overlapped I/O, and thus requires different parameters to ReadFile and WriteFile.Return to topOverridden Property: Length (read-only) Summary Gets the length in bytes of the stream.C# Syntax: public override long�Length {get;} Exceptions
Return to topProperty: Name (read-only) Summary Gets the name of the FileStream that was passed to the constructor.C# Syntax:.NET Framework Security: FileIOPermission for access to the path. Associated enumeration: FileIOPermissionAccess.PathDiscovery Return to topOverridden Property: Position (read-write) Summary Gets or sets the current position of this stream.C# Syntax: public override long�Position {get; set;} Exceptions
In order to open a new file and write to it, set the position to one byte beyond the end of the stream. This allows you to append to the file. The position cannot be set to more than one byte beyond the end of the stream. Example The following is an example of using the Length and Position properties to check for an end-of-file condition. if( s.Length==s.Position ) { Console.WriteLine("End of file has been reached."); }Return to topOverridden Method: BeginRead( ���byte[]�array, ���int�offset, ���int�numBytes, ���AsyncCallback�userCallback, ���object�stateObject )Summary Begins an asynchronous read.C# Syntax:Parameters: array offset numBytes userCallback stateObject
Note Use the FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see Stream.CanRead. If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from BeginRead. Errors that occur during an asynchronous read request, such as a disk failure during the IO request, occur on the threadpool thread and become visible upon a call to FileStream.EndRead. 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. Stream.EndRead must be called with this IAsyncResult to find out how many bytes were read. Multiple simultaneous asynchronous requests render the request completion order uncertain. Return to topOverridden Method: BeginWrite( ���byte[]�array, ���int�offset, ���int�numBytes, ���AsyncCallback�userCallback, ���object�stateObject )Summary Begins an asynchronous write.C# Syntax:Parameters: array offset numBytes userCallback stateObject
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, call the FileStream constructor that has the isAsync parameter. 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 FileStream.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. Stream.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. Return to topOverridden Method: Close()Summary Closes the file and releases any resources associated with the current file stream.C# Syntax: public override void Close(); Exceptions
This implementation of Close calls the FileStream.Dispose method passing a true value. Any data previously written to the buffer is copied to the file before the file stream is closed, so it is not necessary to call FileStream.Flush before invoking Close. Following a call to Close, any operations on the file stream might raise exceptions. After Close has been called once, it does nothing if called again. Flushing the stream will not flush its underlying encoder unless you explicitly call FileStream.Flush or Close. Setting StreamWriter.AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. The FileStream.Finalize method invokes Close so that the file stream is closed before the garbage collector finalizes the object. However, objects writing to the FileStream, such as a StreamWriter, might not have flushed the data from their internal buffers to the FileStream when the call to Finalize closes the stream. To prevent data loss, always call Close on the highest-level object. If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined. Note This version of Close is equivalent to Dispose. Return to topMethod: CreateObjRef( ���Type�requestedType ) Inherited See base class member description: System.MarshalByRefObject.CreateObjRef Summary Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.C# Syntax:
public virtual ObjRef�CreateObjRef( requestedType
Return to topMethod: CreateWaitHandle() Inherited See base class member description: System.IO.Stream.CreateWaitHandle Summary Allocates a WaitHandle object.C# Syntax:Return Value: A reference to the allocated WaitHandle. Remarks When called for the first time, the current method creates a WaitHandle object and returns it. On subsequent calls, the CreateWaitHandle returns a reference to the same wait handle. Use this method if you implement the asynchronous methods and require a way of blocking in Stream.EndRead or Stream.EndWrite until the asynchronous operation is complete. Return to topMethod: Dispose( ���bool�disposing )Summary Releases the unmanaged resources used by the FileStream and optionally releases the managed resources.C# Syntax:
protected virtual void Dispose( disposing Notes to inheritors: FileStream.Dispose may be called multiple times by other objects. When overriding FileStream.Dispose, be careful not to reference objects that have been previously disposed in an earlier call to FileStream.Dispose. This method calls the dispose method of the base class, IDisposable.Dispose. Return to topOverridden Method: EndRead( ���IAsyncResult�asyncResult )Summary Waits for the pending asynchronous read to complete.C# Syntax:Parameters: asyncResult
EndRead can be called on every IAsyncResult from FileStream.BeginRead. Calling EndRead tells you how many bytes were read from the stream.EndRead will block until the I/O operation has completed. Return to topOverridden Method: EndWrite( ���IAsyncResult�asyncResult )Summary Ends an asynchronous write, blocking until the I/O operation has completed.C# Syntax:Parameters: asyncResult
EndWrite must be called exactly once on every IAsyncResult from FileStream.BeginWrite.EndWrite will block until the I/O operation has completed. Return to topMethod: Equals( ���object�obj ) Inherited See base class member description: System.Object.Equals C# Syntax: For more information on members inherited from System.Object click on the link above. Return to topOverridden Method: Finalize()Summary Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream.C# Syntax:Exceptions
Return to topOverridden Method: Flush()Summary Clears all buffers for this stream and causes any buffered data to be written to the underlying device.C# Syntax: public override void Flush(); Exceptions
Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or FileStream.Close. Setting StreamWriter.AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. Because a buffer can be used for either reading or writing, Flush performs the following two functions:
Return to topMethod: GetHashCode() Inherited See base class member description: System.Object.GetHashCodeC# Syntax: public virtual int�GetHashCode(); For more information on members inherited from System.Object click on the link above. Return to topMethod: GetLifetimeService() Inherited See base class member description: System.MarshalByRefObject.GetLifetimeService Summary Retrieves the current lifetime service object that controls the lifetime policy for this instance.C# Syntax: public object�GetLifetimeService(); Return Value: An object of type ILease used to control the lifetime policy for this instance.Remarks For more information about lifetime services, see the LifetimeServices class.Return to topMethod: GetType() Inherited See base class member description: System.Object.GetTypeC# Syntax: For more information on members inherited from System.Object click on the link above. Return to topMethod: InitializeLifetimeService() Inherited See base class member description: System.MarshalByRefObject.InitializeLifetimeService Summary Obtains a lifetime service object to control the lifetime policy for this instance.C# Syntax: public virtual object�InitializeLifetimeService(); Return Value: An object of type ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the LifetimeServices.LeaseManagerPollTime property.Remarks For more information about lifetime services, see the LifetimeServices class.Example The following code example demonstrates creating a lease. public class MyClass : MarshalByRefObject { public override Object InitializeLifetimeService() { ILease lease = (ILease)base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.FromMinutes(1); lease.SponsorshipTimeout = TimeSpan.FromMinutes(2); lease.RenewOnCallTime = TimeSpan.FromSeconds(2); } return lease; } }Return to topMethod: Lock( ���long�position, ���long�length )Summary Prevents access by other processes to all or part of a file.C# Syntax:
public virtual void Lock( position length
Return to topMethod: MemberwiseClone() Inherited See base class member description: System.Object.MemberwiseCloneC# Syntax: protected object�MemberwiseClone(); For more information on members inherited from System.Object click on the link above. Return to topOverridden Method: Read( ���in�byte[] array, ���int�offset, ���int�count )Summary Reads a block of bytes from the stream and writes the data in a given buffer.C# Syntax:
public override int�Read( array offset count
The offset parameter gives the offset of the byte in array (the buffer index) at which to begin writing, and the count parameter gives the maximum number of bytes to be read from this stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged. The Read method returns zero only after reaching the end of the stream. Otherwise, Read always reads at least one byte from the stream before returning. If no data is available from the stream upon a call to Read, the method will block until at least one byte of data can be returned. An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached. Use BinaryReader for reading primitive data types. Example The following is an example of using the Length and Position properties to check for an end-of-file condition. if( s.Length==s.Position ) { Console.WriteLine("End of file has been reached."); }Return to topOverridden Method: ReadByte()Summary Reads a byte from the file and advances the read position one byte.C# Syntax: public override int�ReadByte(); Return Value: The byte cast to an int, or -1 if reading from the end of the stream.Exceptions
Note Use the FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see Stream.CanRead. Notes to implementors: The default implementation on Stream creates a new single-byte array and then calls Stream.Read. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call. Return to topOverridden Method: Seek( ���long�offset, ���SeekOrigin�origin )Summary Sets the current position of this stream to the given value.C# Syntax:Parameters: offset origin
Note Use the FileStream.CanSeek property to determine whether the current instance supports seeking. For additional information, see Stream.CanSeek. Seeking to any location beyond the length of the stream is supported. In order to open a new file and write to it, set the position to one byte beyond the end of the stream. This allows you to append to the file. The position cannot be set to more than one byte beyond the end of the stream. On some platforms, seeking past the end of a file and then doing a write operation results in undefined behavior. Return to topOverridden Method: SetLength( ���long�value ) Summary Sets the length of this stream to the given value.C# Syntax:
public override void SetLength( value
If the given value is less than the current length of the stream, the stream is truncated. If the given value is larger than the current length of the stream, the stream is expanded. If the stream is expanded, the contents of the stream between the old and the new length are undefined. A stream must support both writing and seeking for SetLength to work. Note Use the FileStream.CanWrite property to determine whether the current instance supports writing, and the FileStream.CanSeek property to determine whether seeking is supported. For additional information, see Stream.CanWrite and Stream.CanSeek. Return to topMethod: ToString() Inherited See base class member description: System.Object.ToStringC# Syntax: public virtual string ToString(); For more information on members inherited from System.Object click on the link above. Return to topMethod: Unlock( ���long�position, ���long�length )Summary Allows access by other processes to all or part of a file that was previously locked.C# Syntax:
public virtual void Unlock( position length
Return to topOverridden Method: Write( ���byte[]�array, ���int�offset, ���int�count )Summary Writes a block of bytes to this stream using data from a buffer.C# Syntax:
public override void Write( array offset count
The offset parameter gives the offset of the byte in array (the buffer index) at which to begin reading, and the count parameter gives the maximum number of bytes that will be written to this stream. If the write operation is successful, the current position of the stream is advanced by the number of bytes written. If an exception occurs, the current position of the stream is unchanged. Note Use the FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see Stream.CanWrite. Return to topOverridden Method: WriteByte( ���byte�value )Summary Writes a byte to the current position in the file stream.C# Syntax:
public override void WriteByte( value
Use WriteByte to write a byte to a FileStream efficiently. If the stream is closed or not writable, an exception will be thrown. Note Use the FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see Stream.CanWrite. Notes to implementors: The default implementation on Stream creates a new single-byte array and then calls Stream.Write. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call. Return to topTop of pageCopyright (c) 2002 Microsoft Corporation. All rights reserved.Which method sets the position in the current FileStream?FileStream.Seek(Int64, SeekOrigin) Method (System.IO)
Sets the current position of this stream to the given value.
When using the FileStream class which of the following methods perform synchronous operations?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.
What is the use of FileStream in C#?The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.
What is a FileStream?A FILESTREAM filegroup is a special filegroup that contains file system directories instead of the files themselves. These file system directories are called data containers. Data containers are the interface between Database Engine storage and file system storage.
|