Chapter: C# and .NET Framework

C# FileStreams

A FileStream object is created to process a stream of bytes associated with a backing store —a term used to refer to any storage medium such as disk or memory.

FILESTREAMS FileStreams

 

       A FileStream object is created to process a stream of bytes associated with a backing store —a term used to refer to any storage medium such as disk or memory.

 

       The following code segment demonstrates how it is used for reading and writing bytes: try

 

{

 

// Create FileStream object

 

FileStream fs = new FileStream(@"c:\artists\log.txt",

 

FileMode.OpenOrCreate, FileAccess.ReadWrite);

 

byte[] alpha = new byte[6] {65,66,67,68,69,70}; //ABCDEF

 

//  Write array of bytes to a file

 

//  Equivalent to: fs.Write(alpha,0, alpha.Length); foreach (byte b in alpha) {

 

fs.WriteByte(b);}

 

//  Read bytes from file

 

fs.Position = 0; // Move to beginning of file for (int i = 0; i< fs.Length; i++)

 

Console.Write((char) fs.ReadByte()); //ABCDEF fs.Close();

 

catch(Exception ex)

 

{

 

Console.Write(ex.Message);

 

}

       As this example illustrates, a stream is essentially a byte array with an internal pointer that marks a current location in the stream.

 

       The ReadByte and WriteByte methods process stream bytes in sequence. The Position property moves the internal pointer to any position in the stream.

 

       By opening the FileStream for ReadWrite , the program can intermix reading and writing without closing the file.

 

Creating a FileStream

Ø   The FileStream class has several constructors.

The most useful ones accept the path of the file being associated with the object and optional parameters that define file mode, access rights, and sharing rights. The possible values for these parameters are shown in Figure.


 

        The FileMode enumeration designates how the operating system is to open the file and where to position the file pointer for subsequent reading or writing.

        Table is worth noting because you will see the enumeration used by several classes in the System.IO namespace.

 

 

        The FileAccess enumeration defines how the current FileStream may access the file; FileShare defines how file streams in other processes may access it.

 

        For example, FileShare.Read permits multiple file streams to be created that can simultaneously read the same file.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
C# and .NET Framework : C# FileStreams |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.