C# file input and output
A file is a collection of data stored on disk with a specified name and directory path. When a file is opened for reading and writing, it becomes a stream.
Fundamentally, a stream is a sequence of bytes passed through a communication path. There are two main streams: input stream and output stream. The input stream is used to read data from the file (read operation), and the output stream is used to write data to the file (write operation).
C# I/O class
The System.IO namespace has different classes for performing various file operations, such as creating and deleting files, reading or writing files, closing files, and so on.
The following table lists some of the non-abstract classes commonly used in System.IO namespaces:
I/O class |
Description |
---|---|
BinaryReader |
Read the raw data from the binary stream. |
BinaryWriter |
Write the original data in binary format. |
BufferedStream |
Temporary storage of byte streams. |
Directory |
It helps to manipulate the directory structure. |
DirectoryInfo |
Used to perform operations on the directory. |
DriveInfo |
Provides information about the drive. |
File |
It helps to process files. |
FileInfo |
Used to perform operations on files. |
FileStream |
Used for reading and writing anywhere in the file. |
MemoryStream |
Used to randomly access data streams stored in memory. |
Path |
Perform an operation on the path information. |
StreamReader |
Used to read characters from a byte stream. |
StreamWriter |
Used to write characters to a stream. |
StringReader |
Used to read the string buffer. |
StringWriter |
Used to write to the string buffer. |
FileStream class
In the System.IO namespace FileStream
class helps to read, write and close files. This class is derived from an abstract class Stream
.
You need to create a FileStream
object to create a new file or open an existing file. Create FileStream
syntax of the object is as follows:
FileStream <object_name> = new FileStream( <file_name>,
<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);
For example, create a FileStream
object F
to read the name sample.txt
file:
FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
Parameters. |
Description |
---|---|
FileMode |
The FileMode enumeration defines various methods for opening files. The members of the FileMode enumeration are: ● Append: open an existing file andplace the cursor at the end of the file. If the file does not exist, createthe file. ● Create: create a new file. If the file already exists, delete the old file, and then create a new one. ● CreateNew: specifies that the operating system should create a new file. If the file already exists, an exception is thrown. ● Open: open an existing file. If the file does not exist, an exception is thrown. ● OpenOrCreate: specifies that the operating system should open an existing file. If the file does not exist, a new file is created with the specified name to open. ● Truncate: open an existing file, once opened, it will be truncated to zero byte size. We can then writenew data to the file, but keep the initial creation date of the file. If the file does not exist, an exception is thrown. |
FileAccess |
FileAccess? The members of the enumeration are: Read, ReadWrite? and ?Write. |
FileShare |
The members of the FileShare enumeration are: ● Inheritable: allows file handles to be inherited by child processes. Win32 does not directly support this feature. ● None: declined to share the current file. Any request to open the file (a request from this process or another) will fail before the file is closed. ● Read: allows you to open the file to read later. If this flag is not specified, any requests to open the file for reading (requests made by this process or another process) will fail before the file is closed. However, even if this flag is specified, additional permissions may be required to access the file. ● ReadWrite: allows the file to be opened later for reading or writing. If this flag is not specified, any request to open the file for reading or writing (issued by this process or another process) will fail before the file is closed. However, even if this flag is specified, additional permissions may be required to access the file. ● Write: allows you to open a file to write later. If this flag is not specified, any request to open the file for writing (requests made by this process or another forward process) will fail before the file is closed. However, even if this flag is specified, additional permissions may be required to access the file. ● Delete: allows files to be deleted later. |
Example
The following program demonstrates the usage of FileStream
class:
Example
using System;
using System.IO;
namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat",
FileMode.OpenOrCreate, FileAccess.ReadWrite);
for (int i = 1; i <= 20; i++)
{
F.WriteByte((byte)i);
}
F.Position = 0;
for (int i = 0; i <= 20; i++)
{
Console.Write(F.ReadByte() + " ");
}
F.Close();
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
C # advanced file operations
The above example demonstrates the simple file operation in C#. However, to take full advantage of the power of the C # System.IO classes, you need to know the properties and methods that are commonly used by these classes.
In the following sections, we will discuss these classes and the operations they perform. Please click the link to learn more about each part:
Theme |
Description |
---|---|
Reading and writing of text files |
It involves reading and writing text files. The StreamReader and StreamWriter classes help you read and write text files. |
Reading and writing of binary files |
It involves reading and writing binary files. The BinaryReader and BinaryWriter classes help to read and write binaries. |
Operation of Windows file system |
It allows C # programmers to browse and locate Windows files and directories. |