Skip to main content

FileInfo class in C#

FileInfo class in C#

FileInfo is a class of System.IO namespace and it is useful to perform file operations such as create, read, delete, rename, moving, opening and appending to files.

The FileInfo class will provide the same functionality as File class to manipulate the files but if we are performing multiple operations on the single file, then it’s more efficient to use FileInfo class methods instead of File class methods.

FileInfo class is having a different type of properties and methods to perform operations on files.

FileInfo Properties

The following are the different type of properties which are provided by the FileInfo class to retrieve the information about files.

 

Property

Description

Directory

This property will return an instance of the parent directory of a file.

DirectoryName

It is useful to retrieve the full path of the parent directory of the file.

Exists

This property will return a value that indicates whether the file exists or not.

IsReadOnly

This property is useful to get or set a value that determines whether the current file can be modified or not.

Length

This property will return the size of the current file in bytes.

Name

It is useful to get the name of the file.

Extension

This will return an extension part of the file.

CreationTime

It is useful to get or set the creation time of the current file or directory.

LastAccessTime         

It is useful to get or set the last access time of the current file or directory.

LastWriteTime

It is useful to get or set the time when the current file or directory was last written to.

FileInfo Methods

The table below shows the different type of methods which are provided by FileInfo class to perform a different type of operations on files.


Method

Description

Create        

This method will create a file.

CopyTo(String)

This method will copies an existing file to a new file but it won't allow overwriting an existing file.

CopyTo(String, Boolean)

This method will copies an existing file to a new file and it will allow overwriting an existing file.

CreateText

It creates a StreamWriter that writes a new text file.

AppendText

It creates a StreamWriter that appends a text to the file.

Encrypt     

This method is useful to encrypt a file so that only the account which is used to encrypt the file can decrypt it.

Decrypt

This method is useful to decrypt a file that is encrypted by the current account using the encrypt method.

Delete

This method will delete the file permanently.

Open

It opens a file in the specified mode.

OpenRead

It creates a read-only file stream.

OpenWrite

It creates a write-only file stream.

OpenText

It creates a stream reader that reads from an existing text file.

Replace

This will replace the contents of the specified file with the file described by the current fileinfo object.

ToString

This will return the path as a string.

 

Let’s now see how to use FileInfo class in C# to create, delete, read, move and open operations on file with examples.

 

Using FileInfo Class to Create File in C#

The below code shows the example of creating and writing text to the file using the FileInfo class in C#.

 

using System.IO;

namespace CSharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            string fpath = @"D:\Test.txt";

            // Check file if exists

            if (File.Exists(fpath))

            {

                File.Delete(fpath);

            }

            // Create the file

            FileInfo fi = new FileInfo(fpath);

            //fi.Create();

            // Create and write data to file

            using (StreamWriter sw = fi.CreateText())

            {

                sw.WriteLine("Hi");

                sw.WriteLine("\r\nWelcome to Csharpnaija");

                sw.WriteLine("\r\nFileInfo Example");

            }

        }

    }

}


If we observe the above example carefully, we imported a System.IO namespace in our example to access File, FileInfo & StreamWriter objects to delete, create and write a text to file.


Using FileInfo Class to Read File

In the first example above, we learned how to use the FileInfo class to create and write a text to file. Now, we will learn how to use the FileInfo class to read text from a file.

 

using System;

using System.IO;

namespace CsharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            var fpath = @"D:\Test.txt";

            // Check if file exists

            if (File.Exists(fpath))

            {

                FileInfo fi = new FileInfo(fpath);

                // open the file to read text

                using (StreamReader sr = fi.OpenText())

                {

                    string txt;

                    // Read the data from file, until the end of file is reached

                    while ((txt = sr.ReadLine()) != null)

                    {

                        Console.WriteLine(txt);

                    }

                }

            }

            Console.ReadLine();

        }

    }

}

 

If we observe the above example carefully, we imported a System.IO namespace in our example to access FileInfo & StreamReader object to open and read text from the given file.

We will be looking at the TextReader and TextWriter in the next post where we will use the derived classes of the TextReader and TextWriter classes to write and read files.

 

Thank you

 

References

1.     Tutlane

2.     MicrosoftDocumentation

 

 

Comments

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...