Working with Files in C#.Net

In the C#.Net tutorials, we will see how to handle the file operation in C#.Net? We will also see What are the class and method C#.net provide for file operation like reading data from a file, how to write data to file and how to append data to file? We will discuss some of the methods and classes with some examples for file handling in C#.Net?

We will also see, how to get last modified time of a file in C#.Net, Delete file in C#.Net, Read and write from Text file in C#.Net, How to download file in C#.Net?

We will also discuss here, how to use various c#.net classes like File, FileInfo, Directory, DirectoryInfo class in C#.net to work with file i/o.

Different Classes for File Handling in C#.Net (File I/O in C#.Net)

Now we will see some of the classes, methods, and properties using that we can work with different file operations in C#.Net. Here we will discuss the below class:

  1. File Class
  2. FileInfo Class
  3. Directory Class
  4. DirectoryInfo Class

File Class in C#.Net

Under the System.IO namespace, we can find the File class in c#.net. The File class provides the static methods for creation, copying, deletion, moving and opening a single file, etc.

The methods present under File classes are:

Exists(): The Exist file will determine whether the specified file exists or not in C#.Net. It will return the output in true and false. In the Exist() method we need to pass the file path.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\C#.Net\C#.txt";
            Console.WriteLine(File.Exists(filePath));
        }
    }
}
file.exists() c#
file.exists() c#

ReadAllLines(): The ReadAllLines() method is used to read the text file in C#.net. The ReadAllLines() method will open the file and read all line of the text file and close the file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\C#.Net\C#.txt";
            Console.WriteLine(File.Exists(filePath));
            string[] fileText = File.ReadAllLines(filePath);
            Console.WriteLine(fileText[0]);
            Console.WriteLine(fileText[1]);
        }
    }
}
c# file.readalltext
c# file.readalltext

ReadAllText(): The ReadAllText() method is used to read all the text of file in C#.net. The ReadAllText() method is used to opens a text file, read all lines of a file and then closes the file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\C#.Net\C#.txt";
            Console.WriteLine(File.ReadAllText(filePath));
        }
    }
}
c# file.readalltext
c# file.readalltext

Copy(): The copy() method is used to copies an existing file to a new file, overwriting a file of the same name is not allowed in c#.net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\C#.Net\C#.txt";
            string copyfilePath= @"C:\C#.Net\C#New.txt";
            File.Copy(filePath, copyfilePath);
        }
    }
}
c# file.copy
c# file.copy

Delete(): The Delete() method is used to deletes the specified file in c#.net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\C#.Net\C#.txt";
            File.Delete(filePath);
        }
    }
}
c# file.delete
c# file.delete

WriteAllText(): The File class in c#.net, has WriteAllText() method used to write the text to the specified file but it will not append text it will overwrite the existing text.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\C#.Net\C#New.txt";
            File.Delete(filePath);
            File.WriteAllText(filePath,"New text.It will overwrite the old text");
        }
    }
}
c# file.writealltext
c# file.writealltext

AppendAllText(): The AppendAllText() is used to append text not overwrite the text in the specified file path in C#.net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\C#.Net\C#New.txt";
            File.Delete(filePath);
            File.WriteAllText(filePath,"New text.It will overwrite the old text");
            File.AppendAllText(@"C:\C#.Net\C#New.txt", "I append the  new text");            
        }
    }
}
c#-file.appendalltext
c#-file.appendalltext

AppendAllLines(): The Append AllLines method in c#.net use to append the specified text into the text file. The AppendAllLines() have two parameters one is file path and another one is what text we want to append.

Use AppendAllLines() method to append multiple text lines to the specified file as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\C#.Net\C#New.txt";
            string text= "Tsinfotechnologies" + Environment.NewLine +
                    "is a good devlopement organization" + Environment.NewLine +
                    "for SharePoint";
File.AppendAllLines(filePath, text.Split(Environment.NewLine.ToCharArray()).ToList<string>());
        }
    }
}
c#-file.appendalllines
c#-file.appendalllines

FileInfo Class in C#.Net

FileInfo class in c#.net, provides property, instance method for the creation, copying, deletion, moving and opening of files.

Create(): The Create methods used for creating a new file in specified path.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
           FileInfo fileCreate = new FileInfo(@"C:\C#.Net\Tsinfo.txt");
            fileCreate.Create();           
        }
     }
}
FileInfo Class in C#.Net
FileInfo Class in C#.Net

CreateText(): The CreateText() method in c#.net, is coming under the FileInfo class is used to create a StreamWriter that write a new text file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
          FileInfo fileObj = new FileInfo(@"C:\C#.Net\Tsinfo.txt");
          StreamWriter filewrite= fileObj.CreateText();
          filewrite.WriteLine("I have added some of the text to file");
            filewrite.Close();
        }
     }
}
c# fileinfo write to file
c# fileinfo write to file

Delete(): The Delete method is used to permanently delete a file in c#.Net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
          FileInfo fileObj = new FileInfo(@"C:\C#.Net\Tsinfo.txt");

            fileObj.Delete();
            {
                Console.WriteLine("File is sucessfully deleted");
            }           
        }
     }
}
c# fileinfo delete
c# fileinfo delete

CopyTo(): This CopyTo() method in C#.Net, is used to copy an existing file to a new file and disallowing the overwriting of an existing file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath= @"C:\C#.Net\C#New.txt";
            string filepathdup= @"C:\C#.Net\C#NewDuplicate.txt";
            FileInfo fileobj= new FileInfo(filepath);
            FileInfo filedupobj = new FileInfo(filepathdup);
            fi1.CopyTo(filepathdup);         
        }
     }
}
c# fileinfo copyto
c# fileinfo copyto

MoveTo(): The MoveTo() method is used to moves a specified file to a new location, providing the option to specify a new file name in c#.net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath= @"C:\C#.Net\C#New.txt";
            string filepathdup= @"C:\C#.Net\C#NewDuplicate.txt";
            FileInfo fi1 = new FileInfo(filepath);
            FileInfo fi2 = new FileInfo(filepathdup);
            fi1.MoveTo(filepathdup);           
        }
     }
}
c# file move to

AppendText(): To use the AppendText() method first we need to create the instance for FileInfo Class then we can use the Append text method in c#.net. AppendText method is used to append the text to the specified path location.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo fileObj = new FileInfo(@"C:\C#.Net\C#NewDuplicate.txt");
            StreamWriter strmWr= fileObj.AppendText();
            strmWr.WriteLine("Tsinfo");
            strmWr.WriteLine("SharePoint");
            strmWr.WriteLine("Office365");
            Console.WriteLine("The new text is successfully appended");
            strmWr.Close();
        }
     }
}
c# file append text
c# file append text

OpenText(): The OpenFile method is used to Open the file for reading in C#.net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {                       
            FileInfo fileobj = new FileInfo(@"C:\C#.Net\C#NewDuplicate.txt");
            StreamReader strmread = fileobj.OpenText();
            string fileText = "";
            while ((fileText = strmread.ReadLine()) != null)
            {
                Console.WriteLine(fileText);
            }
        }
     }
}
c#-file-opentext
c#-file-opentext

Directory Class in C#.Net

CreateDirectory(), GetCReationTime(),Exists(): All the method comes under DirectoryClass. The CreateDirectory() is used to create a new directory in a specific location.

GetCreationTime() method will show when the directory is created we need to pass the Directory path in it.

The Exists method is used to show that the directory already exists or not. The output of the Exists method is a boolean value, it will come in yes or no. For the Directory class, it does not need to create an instance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            Directory.CreateDirectory(@"C:\TsinfoTech");
            {
                Console.WriteLine("Your directory sucessfully created");
            }
            Console.WriteLine(Directory.GetCreationTime(@"C:\TsinfoTech"));
            Console.WriteLine(Directory.Exists(@"C:\TsinfoTech"));                       
        }
     }
}
create directory using c#.net
create directory using c#.net

Delete(): The Delete() method is used to delete the specified path empty directories in C#.net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        static void Main(string[] args)
        {
            Directory.Delete(@"C:\TsinfoTech");
            {
                Console.WriteLine("Sucessfully the directory is deleted");
            }
        }
    }
 }
how to delete a directory in c#
how to delete a directory in c#

MoveTo(): The C#.Net Move method is used to move a specified directory to different directory. The Move method has two parameters one is the directory path which you want to move and another one is to which you want to move.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {          
            Directory.CreateDirectory(@"C:\TsinfoTech");
            Directory.Move(@"C:\TsinfoTech", @"C:\TsinfoTechCopyDir");
            {
                Console.WriteLine("Sucessfully the Directory have moved");
            }
        }
    }
 }
how to move directory in c#
how to move directory in c#

DirectoryInfo Class in C#.Net

For using the method the DirectoryInfo class contains we need to create the instance. This method is used to create, delete and move the directory.

Create(): Using the Create() method we can create a directory. In the below code first I have created an instance for DirectoryInfo class and assign to a variable named as dirTnfo. To create the directory we can write dirInfo.Create().

To use all the method under Directory info we need to use the variable name. method name. Then I have written a console statement inside the create method. It will show the message if successfully created then. We can also check the directory exists or not using exists property.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
           String dirPath = @"C:\NewDirectory";
           DirectoryInfo dirInfo = new DirectoryInfo(dirPath);
            dirInfo.Create();
            {
                Console.WriteLine("Sucessfully Created");
            }
            Console.WriteLine(dirInfo.Exists);
        }
     }
 }
directoryinfo-c#
directoryinfo-c#

Create Sub Directory(): This SubDirectory() C#.net method is used to create a subdirectory under the main directory in the specific path. In the CReateSubdirectory method, we need to pass the subdirectory name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {            
            DirectoryInfo dirInfoObj = new DirectoryInfo(@"C:\NewTsinfoDirectory");

       if (dirInfoObj.Exists == false)
            {
                dirInfoObj.Create();
                DirectoryInfo dirInffo = dirInfoObj.CreateSubdirectory("NewSubdirectory");
            }         
        }
    }
}

GetFiles() and GetDirectories(): The GetFiles() method is used to get all the files , specified directory it contains in C#.Net. The GetDirectories method is used to get all the directories the specified directory contains.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo direcInfo = new DirectoryInfo(@"C:\NewTsinfoDirectory");
            DirectoryInfo[] getdirectories= direcInfo.GetDirectories();
            foreach (DirectoryInfo alldirectories in getdirectories)
            {
                Console.WriteLine(alldirectories);
            }
           
            foreach (var allFiles in direcInfo.GetFiles())
            {
                Console.WriteLine(allFiles.Name);
                Console.WriteLine(allFiles.Length);
                Console.WriteLine(allFiles.CreationTime);
            }
        }
    }
}
c# net get files and directories in directoryinfo
c# net get files and directories in directoryinfo

MoveTo(): The MoveTo() method is used to move a directory from one path to different path in C#.net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string directroryPath = @"C:\Tsinfo";
            string directoryPathDup = @"C:\TsinfoDup";
            DirectoryInfo dirInfoObj = new DirectoryInfo(directroryPath);
            DirectoryInfo dirInfoObj2= new DirectoryInfo(directoryPathDup);
            dirInfoObj.MoveTo(directoryPathDup);
                {
                    Console.WriteLine("The Directory successfully moved");
                }
         }
    }
}
how to move directories in info c#
how to move directories in info c#

Delete(): The delete method() is used to delete the directory in C#.Net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        static void Main(string[] args)
        {           
            string directoryPathDup = @"C:\TsinfoDup";         
            DirectoryInfo dirInfoObj2= new DirectoryInfo(directoryPathDup);
            dirInfoObj2.Delete();
                {
                    Console.WriteLine("The Directory successfully deleted");
                }
             }
        }
}
c# delete folder with subfolders and files
c# delete folder with subfolders and files

Encrypt and Decrypt a file in C#.Net

This C#.Net tutorial, we will discuss how to encrypt or decrypt a file in C#.Net.

Encrypt will not allow another user to open and read the file.

To work with files and directory, Microsoft provides System.IO namespace. Here we will use the inbuilt File class to encrypt or decrypt the file.

Encrypt File in C#.Net

Below is the C#.Net code to encrypt file in C#.Net.

string fileToEncrypt = @"C:\AspDotNetHelp";
File.Encrypt(fileToEncrypt);

Decrypt File in C#.Net

Below is the C#.Net code to decrypt file in C#.Net.

string fileToEncrypt = @"C:\AspDotNetHelp";
File.Decrypt(fileToEncrypt);

Here, we learned how to encrypt and decrypt a file in C#.Net.

Get last modified time of a file in C#.Net

Now, we will see how to get the last modified time of a file in C#.Net. To work with files and directory, microsoft provides System.IO namespace.

Below is the sample code that will get the last modified time of the file in C#.Net.

string fileName = @"C:\AspDotNetHelp";
DateTime dt = File.GetLastWriteTime(fileName);
string modifiedTime = dt.ToString();

Similarly you can get the last file access time like below:

string fileName = @"C:\AspDotNetHelp";
DateTime dt = File.LastAccessTime(fileName);
string lastAccessTime = dt.ToString();

Delete file in C#.Net

Now, we will see how to delete a file from a directory in C#.Net.

Microsoft provides System.IO namespace to work with files and directory. Here we will use the FileInfo class to delete the file.

FileInfo class has a delete method that will Delete() the file from the specified location. But before calling the Delete() method it is better to check wether the file is exists or not by using the Exists propertly.

Below is the full C#.Net code to delete file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class DeleteFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DeleteFileFromDrive();
}
void DeleteFileFromDrive()
{
try
{
string path = "C:\\DeleteFile.txt";
FileInfo file = new FileInfo(path);
if (file.Exists)
{
file.Delete();
}
}
catch (Exception ex)
{
throw;
}
}
}

The above code will delete the file from the C drive.

Read and write from Text file in C#.Net

Now, we will see how to read and write from a text file in Asp.net.

You will get a string array while reading all the lines and it will store one line to an array element in C#.Net.

And once you will get the array then you can modify what ever you want and then you can Write the whole array to the file.

Here is the code:

string[] Details = new string[0];
string strPath = @"C:\myfile.txt";
if (File.Exists(strPath))
{
Details = File.ReadAllLines(strPath);
}

//Here you will get in the form of array

Details [0] = "password^###~" + "What ever text you want";

Here you can write the whole array to the file.

File.WriteAllLines(strPath, Details );

Here, we learned how to Read and write from Text file in C#.Net.

How to download file in C#.Net?

Now, we will learn, how to download a file in C#.Net. There are different approaches to download file in C#.Net.

You may like following C#.Net tutorials:

string fileName = @"E:\Filename.txt";

1st Approach:

Response.Clear();
Response.ContentType = "application/octet-stream";// "application/ms-word";
Response.AddHeader("Content-Disposition", "attachment;filename=abc.txt);
Response.WriteFile(fileName);
Response.Flush();
Response.Close();

2nd Approach:

Response.Clear();
Response.ContentType = "application/octet-stream";// "application/ms-word";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + tempFile);
Response.TransmitFile(fileName);
Response.Flush();
Response.Close();

3rd Approach:

Response.Buffer = true;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName);
Response.WriteFile(strFilePath);
Response.Flush();
Response.End();

In the C#.net tutorial, we were discussed what is C#.Net F/O? Which namespace is used for working with C#.Net? What are the class C#.Net provide to working with file input and output system?

We also discussed, how to use File, FileInfo, Directory, DirectoryInfo class in C#.net.

We also discussed, how to get last modified time of a file in C#.Net, Delete file in C#.Net, Read and write from Text file in C#.Net, How to download file in C#.Net?

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SPGuides.com

>