Topic : Working With DirectoryInfo Class | FileInfo Class | Directory



DirectoryInfo Class:

The DirectoryInfo Class is Derived from the FileSystemInfo Class. The DirectoryInfo Class Provides Information about a given directory which can be set through the constructor while creating the DirectoryInfo Object. Once we get a DirectoryInfo Object bound to a directory on the file system, we can get any sort of Information about it including files it contains.



  • » DirectoryInfo class is used for typical operations such as copying, moving, creating or deleting directories.
    » This class cannot be inherited.
    » By default full read/write access to new directories is granted to all users.



Following are some Commonly used Properties of the DirectoryInfo Class:


PropertiesDescription
AttributesGets or sets the Attributes for the current file or Directory.
CreationTimeGets or sets the creation time of the current file or directory.
CreatingTimeUtcGets or sets the Creation time of the current file or directory in coordinated universal time (UTC).
ExistsGets a Boolean value indicating whether the directory exists.
ExtensionGets the string representing the extension part of the file.
FullNameGets the full path of the Directory.
LastAccessTimeGets or sets the time When the current file or directory was last access.
LastAccessTimeUtcGets or sets the time When the current file or directory was last access in Coordinated universal time (UTC).
LastWriteTimeGets or sets the time when the current file or directory was last written to.
LastWriteTimeUtcGets or sets the time when the current file or directory was last written to, in Coordinated Universal time (UTC).
NameGets the name of this DirectoryInfo Instance.
ParentGets the Parent directory of a specified subdirectory.
RootGets the root portion of the directory.


Following are some Commonly Used Methods of the DirectoryInfo Class.


MethodsDescription
Create()Create a Directory.
CreateSubdirectory(string Path)Creates a sub directory or sub directories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.
Delete()Deletes this DirectoryInfo if it is empty.
EnumerateFiles()Returns an Enumerable Collection of file information in the current directory.
Equals(Object)Determines whether the specified object is equal to the current object.
GetDirectories()Returns the Sub directories of the current directory.
GetFiles()Returns a file list from the current directory.
GetType()Gets the Type of the current instance.
MoveTo(String)Moves a DirectoryInfo instance and its contents to a new path.
Refresh()Refreshes the state of the object.
ToString()Returns the Original path that was passed by the user.


The following example demonstrates some of the main members of the DirectoryInfo Class.


/*Example - DirectoryInfo Class - InfoBrother */

using System;
using System.IO;

class DirectoryInfoClass
{
    public static void Main()
    {
        // Specify the directories we  want to manipulate.
        DirectoryInfo DInfo = new DirectoryInfo(@"c:\MyDir");
        try
        {
            // Determine whether the directory exists.
            if (DInfo.Exists)
            {
                // Indicate that the directory already exists.
                Console.WriteLine("That path exists already.");
                return;
            }

            // Try to create the directory.
            DInfo.Create();
            Console.WriteLine("The directory was created successfully.");

            // Delete the directory.
            DInfo.Delete();
            Console.WriteLine("The directory was deleted successfully.");

        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }

        finally { }
        Console.ReadKey();
    }
}

NOTE: For complete list of properties and methods, please visit Microsoft's C# documentation.


FileInfo Class:

FileInfo Class in C# is used for manipulating file as creating, deleting, removing, copying, opening, and getting information. 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.



By default, full read/write access to new files is granted to all users.



Following are some Commonly used Properties of the FileInfo Class:


PropertiesDescription
AttributesGets or sets the attributes for the current file or directory
CreationTimeGets or sets the creation time of the current file or directory.
DirectoryGets an instance of the parent directory.
DirectoryNameGets a string representing the directory's full path.
ExistsGets a value indicating whether a file exists.
ExtensionGets the string representing the extension part of the file.
FullNameGets the full path of the directory or file.
IsReadOnlyGets or sets a value that determines if the current file is read only.
LastAccessTimeGets or sets the time the current file or directory was last accessed.
LastWriteTimeGets or sets the time when the current file or directory was last written to.
LengthGets the size, in bytes, of the current file.
NameGets the name of the file.


Following are some Commonly Used Methods of the FileInfo Class.


MethodDescription
AppendText()Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
CopyTo(String)Copies an existing file to a new file, disallowing the overwriting of an existing file.
Create()Creates a file.
CreateText()Creates a StreamWriter that writes a new text file.
Decrypt()Decrypts a file that was encrypted by the current account using the Encrypt method.
Delete()Permanently deletes a file.
Encrypt()Encrypts a file so that only the account used to encrypt the file can decrypt it.
Equals(Object)Determines whether the specified object is equal to the current object.
GetLifetimeService()Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType()Gets the Type of the current instance.
MoveTo(String)Moves a specified file to a new location, providing the option to specify a new file name.
Open(FileMode)Opens a file in the specified mode.
OpenRead()Creates a read-only FileStream.
OpenText()Creates a StreamReader with UTF8 encoding that reads from an existing text file.
OpenWrite()Creates a write-only FileStream.
Refresh()Refreshes the state of the object.
Replace(String, String)Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file.
ToString()Returns the path as a string.


The following example demonstrates some of the main members of the FileInfo Class.


/*Example - FileInfo Class - InfoBrother*/

using System;
using System.IO;

class FileInfoClass 
{
    public static void Main() 
    {
        string path = Path.GetTempFileName();
        FileInfo File1 = new FileInfo(path);

        //Create a file to write to.
        using (StreamWriter sw = File1.CreateText()) 
        {
            sw.WriteLine("Welcome");
            sw.WriteLine("To");
            sw.WriteLine("InfoBrother");
        }    

        //Open the file to read from.
        using (StreamReader sr = File1.OpenText()) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }

        try 
        {
            string path2 = Path.GetTempFileName();
            FileInfo File2 = new FileInfo(path2); 
            
            //Ensure that the target does not exist.
            File2.Delete();

            //Copy the file.
            File1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);

            //Delete the newly created file.
            File2.Delete();
            Console.WriteLine("{0} was successfully deleted.", path2);

        }

        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }

        Console.ReadKey();
    }
}


NOTE: For complete list of properties and methods, please visit Microsoft's C# documentation.


















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement