Working With FileInfo In C#

Introduction

The System.IO namespace is one of the most significant namespaces for working with Files in the.Net Framework. This article will explain the FileInfo class and its use. Let us see about the class.

FileInfo Class

The FileInfo class does not have static methods and can only be used on instantiated objects. The FileInfo object represents a file on a disk or network location. It also provides instance methods for the creation, copying, deletion, moving, and opening of files and aids in the creation of FileStream objects. Some of the most useful methods of the FileInfo class are,

List of Methods of FileInfo Class, I have included only a few methods of the FileInfo Class.

S.No Methods Description
1 Create This method is used to create the new file.
2 CreateText This Method Creates a StreamWriter that writes a new text file.
3 Delete This method is used to delete an existing file.
4 CopyTo The CopyTo method is used to copy the existing file into a new file.
5 MoveTo The MoveTo method moves the file from one place to another valid location.
6 AppendText This method creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
7 OpenText This method creates a StreamReader with UTF8 encoding that reads from an existing text file.

The methods of the FileInfo class.

FileInfo.Create

This method is used to create the new file.

using System;
using System.IO;

namespace FileInfoClass1
{
    class Program
    {
        // Use a generic attribute with a type parameter
        [Foo<string>("Hello")]
        static void Main(string[] args)
        {
            // Use a raw string literal for the file path
            FileInfo fi = new FileInfo($@"C:\Test\TestFile_Dpk1.txt");
            using StreamWriter str = fi.CreateText();
            Console.WriteLine("File has been created");
            Console.ReadLine();
        }
    }

    // Define a custom generic attribute class
    public class FooAttribute<T> : Attribute
    {
        public T FooProperty { get; set; }
        public FooAttribute(T fooValue) => FooProperty = fooValue;
    }
}

The output of the above code and file created to a targeted location with the file name is shown in the below snapshot.


FileInfo.CreateText

This Method creates a StreamWriter that writes a new text file.

using System;
using System.IO;

namespace FileInfoClass1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use a raw string literal for the file path
            FileInfo fi = new FileInfo(@"C:\Test\TestFile_DpkwithText.txt");
            // Use a using declaration instead of a using statement
            using StreamWriter str = fi.CreateText();
            // Write "hello" to the file
            str.WriteLine("hello");
            Console.WriteLine("File has been created with text.");
            // No need to call str.Close() explicitly
        }
    }
}

The output of the above code and file created with text (hello) to a targeted location with the file name is shown in the below snapshot.


FileInfo.Delete

This method is used to delete an existing file.

using System;
using System.IO;

namespace FileInfoClass2
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use a raw string literal for the file path
            FileInfo fi = new FileInfo(@"C:\Test\TestFile_DpkwithText.txt");
            // Delete the file if it exists
            fi.Delete();
            Console.WriteLine("File has been deleted");
        }
    }
}

The output of the above code is shown in the below snapshot and the targeted file is also deleted.

FileInfo.CopyTo

The CopyTo method is used to copy an existing file into a new file.

using System;
using System.IO;

namespace FileInfoClass3
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use raw string literals for the file paths
            string path = @"C:\Test\New folder\NewText.txt";
            string path2 = @"C:\Test\NewText1.txt";
            FileInfo fi1 = new FileInfo(path);
            FileInfo fi2 = new FileInfo(path2);
            // Copy the first file to the second file
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);
        }
    }
}

The output of the above code is shown in the below snapshot and the targeted file is copied to a specific location.

FileInfo.MoveTo

The MoveTo method moves the file from one place to another valid location.

using System;
using System.IO;

namespace FileInfoClass4
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use raw string literals for the file paths
            string path = @"C:\Test\New folder\NewText.txt";
            string path2 = @"C:\Test\NewText.txt";
            FileInfo fi1 = new FileInfo(path);
            FileInfo fi2 = new FileInfo(path2);
            // Move the first file to the second file
            fi1.MoveTo(path2);
            Console.WriteLine("{0} was moved to {1}.", path, path2);
        }
    }
}

The output of the above code is shown in the below snapshot and the targeted file is moved to a specific location.

FileInfo.AppendText

This method creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.

using System;
using System.IO;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a FileInfo object for the file to append
            FileInfo fi = new FileInfo(@"C:\Test\TestFile_Dpk.txt");

            // Check if the file exists and create it if not
            if (!fi.Exists)
            {
                fi.Create().Close();
            }

            // Open the file in append mode and write some lines
            using (StreamWriter sw = fi.AppendText())
            {
                sw.WriteLine("This");
                sw.WriteLine("is Extra");
                sw.WriteLine("Text");
                Console.WriteLine("File has been appended");
            }
        }
    }
}

The output of the above code is shown in the below snapshot and the required text has been appended to the targeted file.


FileInfo.OpenText

This method creates a StreamReader with UTF8 encoding that reads from an existing text file.

using System;
using System.IO;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a FileInfo object for the file to read
            FileInfo fi = new FileInfo(@"C:\Test\TestFile_Dpk.txt");

            // Check if the file exists and open it in read mode
            if (fi.Exists)
            {
                using (StreamReader sr = fi.OpenText())
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(s);
                    }
                }
            }
            else
            {
                Console.WriteLine("File not found.");
            }
        }
    }
}

The output of the above code is shown in the below snapshot which displays the text available in the targeted file.

FileInfo Properties

namespace FileInfoClass1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo fi = new FileInfo(@"C:\Test\TestFile_Dpk.txt");
            Console.WriteLine($"File name is {fi.Name}");
            Console.WriteLine($"File creation time is {fi.CreationTime.ToLongTimeString()}");
            Console.WriteLine($"File last access time is {fi.LastAccessTime.ToLongDateString()}");
            Console.WriteLine($"File length is {fi.Length.ToString()} Bytes");
            Console.WriteLine($"File extension is {fi.Extension}");
            Console.WriteLine($"File exists: {fi.Exists}");
            Console.WriteLine($"File last write time is {fi.LastWriteTime}");
            Console.ReadLine();
        }
    }
}

Conclusion

The FileInfo class is beneficial for working with files. I expect your valuable comments and feedback about this article. If there is any mistake in this article, then please notify me.


Similar Articles