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...

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...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...