C# File Open: All You Need to Know About It

c# file openC# is a multi-paradigm programming language which has object oriented, component oriented, imperative and functional program features. It is specifically designed by Microsoft for the Common Language Infrastructure. The language is built on the syntax and semantics of the C++ programming language. The goal of C# is to be a simple, modern, general-purpose, object oriented programming language. It forms an important component of Microsoft’s .NET Framework. You can learn more about C# and the .NET framework in this course.

In this tutorial, we’ll walk you through the various aspects of opening and reading a file in C#. We assume that you know the basics of programming. If not, you may want to start with this special C# course, which starts from the basics, and requires no prior programming experience.

C# I/O Classes

A file is a collection of data stored in a disk having a specific name and a directory path. In C#, the System.IO classes are used to handle all file operations – including creating or opening a file, deleting or closing a file a file, and also reading from or writing to a file.

Note that when a particular file is opened for reading or writing, it becomes a stream. In other words the stream is the sequence of bytes passing through the specified communication path. In a nutshell, the input stream is used for reading data from file while the output stream is used for writing into the file.

The most common System.IO classes used to handle files are

  • File: This is kind of the file handle or file name. It used to refer to the file and manipulate it.
  • FileInfo: This is used to perform any actual operations on the file.
  • FileStream: This is used for read or write operations on the file.

There are also other classes that handle directories, binary byte streams, special string usage and even random memory access. To learn more about these you can check out this C# course. With this introduction to the IO class and FileStreams, let’s now see how they are actually used to open and access a file.

C# FileStreams & how to open a file

Like we mentioned above, the FileStream class is what’s used to access files. You need to create a new FileStream to create a new file or open an existing one. Here’s the syntax

FileStream <object_name> = new FileStream( <file_name>,
<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>)

Let’s take a simple example to see how to use it

FileStream myFileStream = new FileStream("myFile.txt", FileMode.Open, FileAccess.Read, FileShare.Read);

While opening a file in this manner, you have to specify the mode you want to open it in (via the FileMode parameter), the access you want it to have (via the FileAccess parameter) and whether you want to share it. Notice that we’ve specified the FileMode as Open.

The FileMode enumerator defines various options while opening files. Here’s the options you can choose

  • Open: This opens an existing file.
  • OpenOrCreate: This specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
  • Append: This opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
  • Create: This creates a new file.
  • CreateNew: This specifies to the operating system, that it should create a new file.
  • Truncate: This opens an existing file and truncates its size to zero bytes.

FileAccess enumerators are simpler and have just the following optionsRead, ReadWrite and Write.

FileShare enumerators have the following options

  • Read: This allows opening the file for reading
  • ReadWrite: This allows opening the file for reading and writing
  • Write: This allows opening the file for writing
  • Inheritable: This allows a file handle to pass inheritance to the child processes
  • None: This declines sharing of the current file

File.Open Method (String, FileMode)

Once you actually have the FileStream, you can finally open the file with the simple Open function. This function is present in the System.IO namespace. Here’s the syntax

public static FileStream Open(
     string path,
     FileMode mode
)

Note that the function has two parameters and one variable value is returned. The function is declared as public. The public keyword is an access specifier which indicates that the function can be accessed from anywhere. The static modifier is used to declare a static member, which belongs to the type itself instead of a specific object. The path variable is of type System.String and indicates which file to open. The mode variable is of type System.IO.FileMode. The value determines whether a file is created in case of non existing file. Also determines whether the contents of the files present are retained or overwritten. The return value is of type System.IO.FileStream.  To learn more about how to write your own code with files, with practical examples, you can take this beginners tutorial on C#.

Now let’s see how it all comes together to open a file with following program, where we open a file, put some data into it, and then read the data back (detailed explanation after the program).

using System;
using System.IO;
using System.Text;
class NewTest
{
    public static void Main()
    {
         string newpath = Path.GetTempFileName();
        using (FileStream fs = File.Open(newpath, FileMode.Open, FileAccess.Write, FileShare.None))
        {
            Byte[]newinfo = new UTF8Encoding(true).GetBytes("This is some text in the file.");
             fs.Write(newinfo, 0, newinfo.Length);
        }
        using (FileStream fs = File.Open(newpath, FileMode.Open))
        {
            byte[] b1 = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
             while (fs.Read(b1,0,b1.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b1));
            }
        }
    }
}

At the beginning of the program, the ‘using’ operator includes the namespaces (System, System.IO and System. Text) in the code. In other words the program can now use any of the classes present in those namespaces.The variable newtest is declared to be of type class. Now it can contain variables and functions. The main function is the place where the execution of the program starts. The C# Path.GetTempFileName function creates a uniquely named, zero-byte temporary file on the disk and returns the full path of that file. FileMode.Open opens an existing file. FileShare.None declines sharing of the current file. UTF8Encoding is a specific method to handle text that may be in UTF8 encoding. The ‘UTF8Encoding’ function puts the text into a Byte array called ‘newinfo’. The read and write file functions are used to write info into the file and read info from the file respectively. The read operation terminates when the file ends.

While writing your own programs, you need to be careful of the parameters you pass to the File Open function. If you pass invalid parameters, ou may get an Exception. The most common exceptions thrown by File Open  function are

  • ArgumentException
  • ArgumentNullException
  • PathTooLongException
  • DirectoryNotFoundException
  • IOException
  • ArgumentOutOfRangeException
  • UnauthorizedAccessException
  • FileNotFoundException
  • NotSupportedException

The best way to learn to program – is to try it out for yourself. So go ahead and try these examples, and come up with some more of your own. It’s okay if you get a few exceptions in your initial programs. If you need more in depth help on C#, feel free to jump over to our Live Lessons on C# Fundamentals (Part I and Part II)