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

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...