File Handling using C#

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

File handling and editing is something you should know how to deal with, since a lot of info is stored within simple files. We will go through the basics of file handling such as creating, deleting, moving and copying files. Next we are going to read and write to files. We will sum everything up using an example where we will be able to handle two files.

 
file handling
 

Getting started

We are about to go through the basics of file handling. To do this we will use two files, a primary and a secondary, both named as text.txt. One located in my D:\Projects\DotNetHintsBlog\EditFiles folder; the second located in my D:\\Projects\DotNetHintsBlog\EditFiles\FolderToMoveFiles folder. These paths I declare on top of my class.
 
string PrimaryFilePath = "D:\\Projects\\DotNetHintsBlog\\EditFiles\\text.txt";
string SecondaryFilePath = "D:\\Projects\\DotNetHintsBlog\\EditFiles\\FolderToMoveFiles\\text.txt";
 
Needless to say, you may use your own personal files instead of mine.
 
We will create handling methods for both of them that can be executed by pressing the right button like it's shown in the following picture.
 
 
Both file handlers will call the same method. After you take a look at the examples you will easily get the point. Let's start off by creating files.
 

Creating files

Most examples will use the System.IO.File class. Right now we are going to use the File.Create method.
 
Here's the .aspx file
 
<asp:Button runat="server" ID="CreatePrimaryFileButtonID" Text = "Create Primary File" OnClick ="CreatePrimaryFileButtonClicked" />
<br />
<asp:Button runat="server" ID="CreateSecondaryFileButtonID" Text= "Create Secondary File" OnClick ="CreateSecondaryFileButtonClicked" />
<br />
 
The .aspx.cs file
 
 #region  Create files
    protected void CreatePrimaryFileButtonClicked(object sender, EventArgs e)
    {
        //Creates Primary File
        CreateFile("Primary");
    }
 
    protected void CreateSecondaryFileButtonClicked(object sender, EventArgs e)
    {
        //Creates Secondary File
        CreateFile("Secondary");
    }
 
    private void CreateFile(string primaryType)
    {
        string filePath = PrimaryFilePath;
        if (primaryType != "Primary")
            filePath = SecondaryFilePath;
 
        //Check if file exists
        if (!File.Exists(filePath))
        {
            // Creates new file
            File.Create(filePath);
            InfoLabelID.Text = primaryType + " file succesfully created.";
        }
        else
            InfoLabelID.Text = primaryType + " file already exists.";
 
    }
 
    #endregion  Create files
 
 
Both handlers call the CreateFile method, using a different string argument. This will result in creating the corresponding file and message.
 
Before we call the File.Create method we need to ensure that the file does not already exist. To do this we use the File.Exists method. If it exists, we get a message telling as so. If it does not exist, we can create it using the File.Create.  If we use File.Create while the file already exists, we will get no exception. Our old file will however be replaced by the new one.
 
 
delete files
 

Deleting Files

Moving on in the same way, we create two more buttons that will delete our files.
 
<asp:Button runat="server" ID="DeletePrimaryFileButtonID" Text = "Delete Primary File" OnClick ="DeletePrimaryFileButtonClicked" />
<br />
<asp:Button runat="server" ID="DeleteSecondaryFileButtonID" Text = "Delete Secondary File" OnClick ="DeleteSecondaryFileButtonClicked" />
 
 
To delete a file we will use the File.Delete method that will simply delete our file. Using File.Delete to delete a file that doesn't exist will not throw an exception. However it would be a good idea keep an eye on this and inform the user in such case. Here's our source code.
 
 #region Delete Files
    protected void DeletePrimaryFileButtonClicked(object sender, EventArgs e)
    {
        //Deletes Primary File
        DeleteFile("Primary");
    }
 
    protected void DeleteSecondaryFileButtonClicked(object sender, EventArgs e)
    {
        //Deletes Secondary File
        DeleteFile("Secondary");
    }
 
    private void DeleteFile(string primaryType)
    {
        string filePath = PrimaryFilePath;
        if (primaryType != "Primary")
            filePath = SecondaryFilePath;
 
        //Check if file exists
        if (File.Exists(filePath))
        {
            // Deletes new file
            File.Delete(filePath);
            InfoLabelID.Text = primaryType + " file succesfully deleted";
        }
        else
            InfoLabelID.Text = primaryType + " file does not exist.";
    }
 
    #endregion Delete Files 
 
 
 

Moving and Copying files

Next thing to do is to see how we can move or copy the primary file to the secondary. It's quite easy. We will just use File.Move and File.Copy methods and supply them with our file paths as arguments. Here's the code using our familiar buttons.
 
<asp:Button runat="server" ID="CopyPrimaryFileToSecondaryButtonID" Text = "Copy Primary File To Secondary" OnClick ="CopyPrimaryFileToSecondaryButtonClicked" />
<br />
<asp:Button runat="server" ID="MovePrimaryFileToSecondaryButtonID" Text = "Move Primary File To Secondary" OnClick ="MovePrimaryFileToSecondaryButtonClicked" /> 
 
 protected void CopyPrimaryFileToSecondaryButtonClicked(object sender, EventArgs e)
{
   //Check if circumstances are met
   if (File.Exists(PrimaryFilePath))
   {
      if (!File.Exists(SecondaryFilePath))
      {
         //Copy primary file to secondary
         File.Copy(PrimaryFilePath, SecondaryFilePath);
         InfoLabelID.Text = "Successfully copied primary file to secondary.";
      }
      else
         InfoLabelID.Text = "Secondary file already exists.";
   }
  else
        InfoLabelID.Text = "Primary file does not exist.";
}
 
protected void MovePrimaryFileToSecondaryButtonClicked(object sender, EventArgs e)
{
   //Check if circumstances are met
   if (File.Exists(PrimaryFilePath))
   {
      if (!File.Exists(SecondaryFilePath))
         {
            //Move primary file to secondary
            File.Move(PrimaryFilePath, SecondaryFilePath);
            InfoLabelID.Text = "Successfully moved primary file to secondary.";
         }
      else
            InfoLabelID.Text = "Secondary file already exists.";
   }
   else
     InfoLabelID.Text = "Primary file does not exist.";
}
 
It is a good idea to check if the files specified exist or not ,before advancing. For example, in case we wanted to copy our file in a folder where a file with the same name exists we could inform the user by asking "The specified folder already contains a file named file_name. Do you really wish to delete it?".
 

Reading files

So far, we've taken into account actions that apply to all types of file. We are now going to see how actions that suit best in files containing text, work. First action, is how to read a file.
 
When applying input/ output operations to a file we can use stream methods instead of file methods. Consider a stream as the sequence of bytes that are transferred while the File represents the file itself. A stream can be used to read, write or search within a file, but is unable to do more than one things at a time. Even though using a stream can be faster than a file, file methods tend be more developer friendly.
 
To read a file's content we can use both the File class methods, such as File.ReadAllText or a StreamReader. A StreamReader is the class that Stream offers in order to accomplish a reading action.. To use it, we should place it in a TextReader object. After that, we can use its methods. For example:
 
TextReader reader = new StreamReader(filePath);
 
Don't forget to close the TextReader object after you are done.
 
Here's our example, where we will place the content within a label.
 
 <asp:Button runat="server" ID="ReadPrimaryFileButtonID" Text  = "Read Primary File" OnClick ="ReadPrimaryFileButtonClicked" />
   <br />
 <asp:Button runat="server" ID="ReadSecondaryFileButtonID" Text = "Read Secondary File" OnClick ="ReadSecondaryFileButtonClicked" />
  <br />
  <asp:Label  runat="server" ID="InfoLabelID" />
 
    #region  Read files
    protected void ReadPrimaryFileButtonClicked(object sender, EventArgs e)
    {
        //Reads Primary File
        ReadFile("Primary");
    }
 
    protected void ReadSecondaryFileButtonClicked(object sender, EventArgs e)
    {
        //Reads Secondary File
        ReadFile("Secondary");
    }
 
    private void ReadFile(string primaryType)
    {
        string filePath = PrimaryFilePath;
        if (primaryType != "Primary")
            filePath = SecondaryFilePath;
 
        if (File.Exists(filePath))
        {
            // Reads file
            string fileText = File.ReadAllText(filePath);
            InfoLabelID.Text = string.Format("{0}  filePath content :  {1}", primaryType, fileText);
 
            //We could use a StreamReader instead
            //TextReader reader = new StreamReader(filePath);
            //InfoLabelID.Text = string.Format("{0}  filePath content :  {1}", primaryType, reader.ReadToEnd());
            //reader.Close();
            
        }
        else
            InfoLabelID.Text = primaryType + " file does not exist.";
 
    }
 
    #endregion  Read files
 

Write on files

Similar to the way we can read a file, we can write content inside it. Writing means that its content is replaced by the new content, not just added to the present content. This is what append does, which we will see right after that.
 
Like reading a file, we can use both the File class (eg File.WriteAllText) and the StreamWriter class methods. A StreamWriter is like a StreamReader. It writes on a file using a stream. We will now use a TextWriter instead of the TextReader. This way, we can write to a file like this:
 
TextWriter writer = new StreamWriter(filePath);
writer.Write(textToWrite);
 
Don't forget to close the TextWriter object after you are done writing as well.
 
Here's our example, where we will place the new content within a textbox.
 
 <asp:Button runat="server" ID="WritePrimaryFileButtonID" Text = "Write to Primary File" OnClick ="WritePrimaryFileButtonClicked" />
    <br />
    <asp:Button runat="server" ID="WriteSecondaryFileButtonID" Text = "Write to Secondary File" OnClick ="WriteSecondaryFileButtonClicked" />
    <br />
Insert new text here : <asp:TextBox runat="server" ID="TextBoxID" />
 
    #region  Write to files
    protected void WritePrimaryFileButtonClicked(object sender, EventArgs e)
    {
        //Write to Primary File
        WriteFile("Primary");
 
    }
 
    protected void WriteSecondaryFileButtonClicked(object sender, EventArgs e)
    {
        //Write to Secondary File
        WriteFile("Secondary");
    }
 
    private void WriteFile(string primaryType)
    {
        string filePath = PrimaryFilePath;
        if (primaryType != "Primary")
            filePath = SecondaryFilePath;
 
        string textToWrite = TextBoxID.Text;
 
        // Writes to file
        File.WriteAllText(filePath, textToWrite);
        InfoLabelID.Text = "Successfully wrote text to " + primaryType + "file";
 
        //We could use a StreamWriter instead
        //TextWriter writer = new StreamWriter(filePath);
        //writer.Write(textToWrite);
        //writer.Close();
        //InfoLabelID.Text = "Successfully wrote text to " + primaryType + "file";
 
    }
 
    #endregion  Write files
 
 

Append files

As mentioned earlier, when writing, the current content is replaced by the new content. If the only thing we want is to add content, we can use other methods the File class offers, for example the File.AppendAllText. It is quite similar to the way we call File.WriteAllText method.
 
Here's our example.
 
    <asp:Button runat="server" ID="AppendPrimaryFileButtonID" Text = "Append Primary File" OnClick="AppendPrimaryFileButtonClicked" />
    <br />
    <asp:Button runat="server" ID="AppendSecondaryFileButtonID" Text = "Append Secondary File" OnClick="AppendSecondaryFileButtonClicked" />
    <br />
    Insert new text here : <asp:TextBox runat="server" ID="TextBoxID" />
 
#region  Append files
    protected void AppendPrimaryFileButtonClicked(object sender, EventArgs e)
    {
        //Appends Primary File
        AppendFile("Primary");
    }
 
    protected void AppendSecondaryFileButtonClicked(object sender, EventArgs e)
    {
        //Appends Secondary File
        AppendFile("Secondary");
    }
 
    private void AppendFile(string primaryType)
    {
        string filePath = PrimaryFilePath;
        if (primaryType != "Primary")
            filePath = SecondaryFilePath;
 
        //Gets text from textbox
        string textToAppend = TextBoxID.Text;
 
        // Appends file
        File.AppendAllText(filePath, textToAppend);
        InfoLabelID.Text = "Successfully appended text to " + primaryType + "file";
    }
 
    #endregion  Append files
 
 

Conclusion 

We have learned how the, probably, most common file actions you might want to do work. Combining all the pieces of source code given earlier you can create a simple user interface where you can test all the methods mentioned. Enjoy, but keep in mind that some methods may lock your file for a small amount, causing an IOException to be thrown stating that you can't use the file because it is being used by another process.
 
 
 

 

Back to BlogPreviousNext

Comments



    Leave a comment
    Name: