Reading and Writing Files with C# and .NET Framework
Properties
Name | Description |
---|---|
CanRead | Decides if stream supports reading. |
CanSeek | Decides if stream supports seeking. |
CanTimeout | Decides if stream can time out. |
CanWrite | Decides whether the stream can be written to. |
Length | Determines the length of the stream. |
Position | Determines or sets the virtual cursor. |
ReadTimeout | Determines or sets the stream's timeout for read. |
WriteTimeout | Determines or sets the stream's timeout for write. |
Methods
Name | Description |
---|---|
Close | Closes the stream and discharge any resources. |
Flush | Clears out any buffers within the stream. |
Read | Sequential read of a specified number of bytes. |
ReadByte | Does the read of a single byte and updates position by one. |
Seek | Sets the position within the stream. |
SetLength | Determines the length of the stream. |
Write | Writes information to the stream. |
WriteByte | Writes a single byte to the stream. |
All the Stream Classes such as FileStream (System.IO), MemoryStream (System.IO), CryptoStream (System.Security), NetworkStream (System.Net), GZipStream (System.Compression) derived from Stream Class. The main reason is that they are all working in a similar way.
//Display Stream
static void DumpMyStream(Stream theMyStream)
{
theMyStream.Position = 0;
while (theMyStream.Position != theMyStream.Length)
{
Console.WriteLine("{0:x2}", theMyStream.ReadByte());
}
}
We require a file to read from or to it with the help of Stream class or its derivatives. In order to access file and assist Stream class to work with the file we employ File class.
Methods of the File class
Name | Description |
---|---|
AppendAllText | Appends a string into a file. |
AppendText | Opens a file with the StreamWriter. |
Copy | Copies a file to a new file. |
Create | Creates a new file. |
CreateText | Creates or opens a file. |
Move | Moves a file from one place to another. |
Open | Opens an existing file. |
OpenRead | Reads an existing read-only file. |
OpenText | Reads an existing file. |
OpenWrite | Reads an existing file for writing. |
ReadAllBytes | Reads a file, reads the contents. |
ReadAllLines | Reads a file, reads the contents of it into an array of strings. |
ReadAllText | Reads the contents of it into a string. |
WriteAllBytes | Writes a file content of a byte array. |
WriteAllLines | Writes a file, writes the contents of a string array. |
WriteAllText | Writes the contents of a string into a file. |
In addition to File class that helps us to work with files, .NET Framework provides Directory class which helps us to work with directories as its name suggests.
Methods
Name | Description |
---|---|
CreateDirectory | Creates the directories. |
Delete | Deletes a directory. |
Exists | Checks for existence. |
GetCreationTime | Get time and date of a directory creation. |
GetCurrentDirectory | Gets a DirectoryInfo object. |
GetDirectories | Gets names for subdirectories. |
GetDirectoryRoot | Gets the volume and/or root information. |
GetFiles | Gets the names of files. |
GetFileSystemEntries | Gets a list of subdirectories. |
GetLastAccessTime | Gets the time that dir. was last accessed. |
GetLastWriteTime | Gets the time that dir. was last written to. |
GetLogicalDrives | Gets a list of drives. |
GetParent | Gets the parent directory. |
Move | Moves a file or directory. |
SetCreationTime | Sets the time a when directory was created. |
SetCurrentDirectory | Sets the specified directory to be the current working directory. |
SetLastAccessTime | Sets the time a directory was accessed. |
SetLastWriteTime | Sets the time a directory was written to. |
In order to access file we need to set a mode in which way we want to access Read/Write. In order to do that we use FileAccess enumeration this has following members.
Name | Description |
---|---|
Read | Open with read-only access. |
Write | Open for write access only. |
ReadWrite | Open for read/write access. |
FileMode enumeration determines how we are going to work with the file. We can open file, create new one and etc… Its main members are:
Name | Description |
---|---|
Append | Append a file and moves the pointer in the FileStream. |
Create | Creates a new file. |
CreateNew | Creates a new file with the exception thrown. |
Open | Opens an existing file. |
OpenOrCreate | Opens an existing file or creates new. |
Truncate | Opens and Trancates file. |
Additional classes which are important to know: FileStream class used to open file stream for reading or writing.
Properties
Name | Description |
---|---|
Handle | Determines the stream's file handle. |
Name | Determines the name of the file. |
Methods
Name | Description |
---|---|
Lock | Lock file for changes. |
Unlock | Unlocks file for changes. |
StreamReader class as its name suggests is used for reading streams.
Properties
Name | Description |
---|---|
BaseStream | Gets the base stream. |
CurrentEncoding | Gets the encoding used for the stream. |
EndOfStream | Determines the end of the stream. |
Methods
Name | Description |
---|---|
Close | Closes the reader and the stream. |
Peek | Returns the next character without moving. |
Read | Reads the next set of characters. |
ReadBlock | Reads the next block of characters. |
ReadLine | Reads the next line of characters. |
ReadToEnd | Reads all the characters till the end of the stream. |
Reading from the file is simple, we first open file like that. FileStream is already buffered stream so it does not require BufferedStream object.
FileStream myFileStream = File.Open(@"C:\boot.ini", FileMode.Open, FileAccess.Read);
In order to read this file we can use Read class but better way is to utilize StreamReader class
StreamReader myRDR = new StreamReader(myFileStream);
Console.Write(myRDR.ReadToEnd());
myRDR.Close();
myFileStream.Close();
Or you can use the following way of opening and reading file. Here we can see that File class supports StreamReader
StreamReader myRDR = File.OpenText(@"C:\bootfile.ini");
Console.Write(myRDR.ReadToEnd());
myRDR.Close();
StreamWriter Class is similar to StreamReader in several ways; it uses File class pretty much the same way as StreamReader.
Properties
Name | Description |
---|---|
AutoFlush | Gets or sets an indicator that shows flush changes to the stream. |
BaseStream | Gets the current stream. |
Encoding | Gets the current encoding used for the stream. |
NewLine | Gets or sets a string that contains the line terminator string. |
Methods
Name | Description |
---|---|
Close | Closes the writer of the stream. |
Write | Writes to the stream. |
WriteLine | Writes data to the stream with line end. |
Example if writing a file in C# as follows.
Open file
FileStream myFileStream = File.Create(@"c:\somefilestream.txt");
Write to file
StreamWriter myWriter = new StreamWriter(myFileStream);
myWriter.WriteLine("Hello");
myWriter.Close();
myFileStream.Close();