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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

Interface with real life Examples

Interfaces with real life examples An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a tricyclic class and a truck class. Each of these three classes should have a start engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that  they must  have a start engine action is the domain of the interface. The syntax of an Interface We can implement single interface or multiple interfaces to the class. By default interfaces are public. We declare interface by using "interface" keyword. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CsharpnaijaInterfaceTutorial {     interface IEngine     {         void Start();     }...

The Out Parameter with Example in C#

  The Out Parameter with Example in C# In C#,  out  keyword is used to pass arguments to the method as a  reference type . The  out  keyword same as the  ref  keyword but the only difference is  out  doesn’t require a variable to be initialized before we pass it as an argument to the method but the  variable  must be initialized in called method before it returns a value to the calling method. The out parameter in C# is also useful to return more than one value from methods. Declaration of C# Out Parameter Following is a simple example of using  out  parameters in C#.   int x; // No need to initialize variable OutParameterMultTest ( out x ) ;   From the above declaration, we just declared a variable  x  and pass it to the method by using  out  parameter without assigning any value but as discussed, the variable must be initialized in called method before it returns a value...