C# FileInfo Class with Programming Example and Code

In this chapter you will learn:
  • What is FileInfo class in C#?
  • How to use FileInfo to create, delete or move file?
  • Programming Examples and Codes

What is FileInfo class in C#?

FileInfo class in c# is used for manipulating file as creating, deleting, removing, copying, opening and getting information. It provides properties and instance methods that makes file manipulation easy.

Notes

  1. FileInfo class is used for typical operation like copying, moving, renaming, creating, opening, deleting and appending the file.
  2. By default, full read/write access to new files is granted to all users.

How to use FileInfo to manipulate file?

The following program demonstrates well the uses of FileInfo class. This program searches for file D:\csharp\fileinfo.txt. If the file found then it displays the information of the file else create new file.

 

Programming Examples and Codes

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

namespace FileInfo_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"D:\csharp\fileinfo.txt";
            FileInfo file = new FileInfo(path);
            //Create File
            using (StreamWriter sw = file.CreateText())
            {
                sw.WriteLine("Hello FileInfo");
            }

            //Display File Info            
            Console.WriteLine("File Create on : " + file.CreationTime);
            Console.WriteLine("Directory Name : " + file.DirectoryName);
            Console.WriteLine("Full Name of File : " + file.FullName);
            Console.WriteLine("File is Last Accessed on : " + file.LastAccessTime);
            
            //Deleting File
            Console.WriteLine("Press small y for delete this file");
            try
            {
                char ch = Convert.ToChar(Console.ReadLine());
                if (ch == 'y')
                {
                    if (file.Exists)
                    {
                        file.Delete();
                        Console.WriteLine(path + " Deleted Successfully");
                    }
                    else
                    {
                        Console.WriteLine("File doesn't exist");
                    }
                }                
            }
            catch
            {
                Console.WriteLine("Press Enter to Exit");
            }
            Console.ReadKey();
        }
    }
}

Output
File Create on : 13-08-2016 PM 12:49:36
Directory Name : D:\csharp
Full Name of File : D:\csharp\fileinfo.txt
File is Last Accessed on : 13-08-2016 PM 12:49:36
Press small y for delete this file_

Summary

In this chapter you learned implementation of FileInfo class in C# with complete programming examples. In the next chapter you will learn programming examples of file handling.

 

Share your thought