Working with files and directories - Part 2

Naimishforu
Posted by in C# category on for Beginner level | Points: 250 | Views : 4402 red flag

We will see how to work with files and directories

Introduction


One of the basic functions of the System.IO class is to examine the contents of directories to discover which files and folders it contains, as illustrated by the following program.

Any program that works with the file system should start by declaring that it is using the System.IO namespace.

using System;
using System.IO;

namespace FilesAndFolders
{
  /// 
  /// Summary description for Class1.
  /// 
  class FilesFolders
  {
    protected void ProcessThisFileOrFolder(string ThePathName)
    {
      try
      {
        DirectoryInfo ThisFolder = new DirectoryInfo(ThePathName);
        if (ThisFolder.Exists)
        {

          ListContentsOfThisFolder(ThisFolder);
          return;
		}
	  }
	}
  }
}

The following method checks if a given pathname is a folder or a file. If it's a folder, the method locates it and retrieves information about it.

using System;
using System.IO;

namespace FilesAndFolders
{
  /// 
  /// Summary description for Class1.
  /// 

  class FilesFolders
  {
    protected void ProcessThisFileOrFolder(string ThePathName)
    {
      try
      {
        DirectoryInfo ThisFolder = new DirectoryInfo(ThePathName);
        if (ThisFolder.Exists)
        {
          ListContentsOfThisFolder(ThisFolder);
          return;
        }
      }
    }
  }
}

If it's not a folder, the method checks to see if it's a file. If it is a file, the method locates the file and retrieves information about it.

It checks to see whether the folder and file exist using the Exists method.

The ListContentsOfThisFolder method is called if the folder exists at the path given, and the DisplayFileInfo method is called if the file exists at the path given.

The return statements are used to terminate execution of this method and return control to the calling method.

protected void ProcessThisFileOrFolder(string ThePathName)
{
  try
  {
    DirectoryInfo ThisFolder = new DirectoryInfo(ThePathName);
    if (ThisFolder.Exists)
    {
      ListContentsOfThisFolder(ThisFolder);
      return;
    }

    FileInfo ThisFile = new FileInfo(ThePathName);
    if (ThisFile.Exists)
    {
      DisplayFileInfo(ThisFile);
      return;
    }
    throw new FileNotFoundException();
  }
}

The following line creates a new DirectoryInfo object for the specified location.

DirectoryInfo ThisFolder = new DirectoryInfo(ThePathName);

The following line creates a FileInfo object for the specified location.

FileInfo ThisFile = new FileInfo(ThePathName);

If the path doesn't lead to anything, a FileNotFoundException is thrown.

        FileInfo ThisFile = new FileInfo(ThePathName);
        if (ThisFile.Exists)
        {
          DisplayFileInfo(ThisFile);
          return;
        }
        throw new FileNotFoundException();
      }
      catch(FileNotFoundException)
      {
        Console.WriteLine(ThePathName + " This file or folder does not exist");
      }
      catch(Exception e)
      {
        Console.WriteLine(ThePathName + " Problem occurred:");
        Console.WriteLine(e.Message);
      }

The DisplayFileInfo method examines the FileInfo object created by the ProcessThisFileOrFolder method and writes information about the file to the console.

The filename, creation time, last access time, last write time, and file size are written to screen.

protected void DisplayFileInfo(FileInfo ThisFile)
{
      Console.WriteLine("\n\nFile Information");
      Console.WriteLine("----------------");
      Console.WriteLine("File name: " + ThisFile.Name);
      Console.WriteLine("Creation time: " + ThisFile.CreationTime.ToLongTimeString());
      Console.WriteLine("Last access time: " + ThisFile.LastAccessTime.ToLongDateString());
      Console.WriteLine("Last write time: " + ThisFile.LastWriteTime.ToLongDateString());
      Console.WriteLine("Length: " + ThisFile.Length.ToString() + " bytes");
}

The ListContentsOfThisFolder method returns information about the DirectoryInfo object. 

All the names of files and folders within the specified pathname are written to screen.

protected void ListContentsOfThisFolder(DirectoryInfo Parent)
{
      Console.WriteLine("Current parent path: " + Parent.FullName);
      Console.WriteLine("FILES:");
      Console.WriteLine("------");
      foreach(FileInfo NextFile in Parent.GetFiles())
      {
        Console.WriteLine(NextFile.Name);
      }
      Console.WriteLine("");
      Console.WriteLine("FOLDERS:");
      Console.WriteLine("--------");
     foreach(DirectoryInfo NextFolder in Parent.GetDirectories())
     {
        Console.WriteLine(NextFolder.Name);
     }
}

The Main method is the starting point for this program. It creates instances of the FilesFolders class, and the ProcessThisFileOrFolder method is called to process C:/DotNet and Hello.cs.

The methods in the System.IO namespace are also used for creating, moving, and deleting files, as is demonstrated by this program, which contains methods for performing each of these tasks.

The program should start by declaring the namespaces it is using.

using System;
using System.IO;

namespace FilesAndFolders
{
  /// 
  /// Summary description for Class1.
  /// 

  class FilesFolders
  {
    protected void ProcessThisFileOrFolder(string ThePathName)
    {
      try
      {
        DirectoryInfo ThisFolder = new DirectoryInfo(ThePathName);

        if (ThisFolder.Exists)
        {
          ListContentsOfThisFolder(ThisFolder);
          return;
        }
      }
    }
  }
}

The CreateThisFile method of this program creates a new file when supplied with the name to be used for the file.

It uses the Create method, which is part of the FileInfo and File classes to create the specified file.

protected void CreateThisFile(string TheFileName)
    {
      try
      {
        Console.WriteLine("File creation:");
        Console.WriteLine("--------------");

        File.Create(TheFileName);
        Console.WriteLine(TheFileName + " has been created.");
        Console.WriteLine("\n\nCalling ProcessThisFileOrFolder again");
        ProcessThisFileOrFolder(TheFileName);
      }
      catch(Exception e)
      {
        Console.WriteLine("Unable tocreate file. The following exceptionoccurred:\n" + e.Message, "Failed");
      }

If the program can't execute for some reason, an exception is thrown.

The DeleteThisFile method removes a named file from the system.

Because of the risk of losing valuable data, it is good practice to make sure the user wishes to delete the file.

The file is actually deleted using the Delete method, which is part of the FileInfo and File classes.

protected void DeleteThisFile(string TheFileName)
    {
      try
      {
        Console.WriteLine("\nFile deletion:");
        Console.WriteLine("--------------");
        StringQuery = "Are you sure you want to delete\n" + TheFileName + "? ";

        Console.WriteLine(Query + "\nEnter 1 for Yes or 0 for No ");
        //parse what the user has entered
        int index = Int32.Parse(Console.ReadLine());

        //Delete if user enters 1 for Yes
        if (index == 1)
        {

          File.Delete(TheFileName);
          Console.WriteLine(TheFileName + " has been deleted.");
          Console.WriteLine("\n\nCalling ProcessThisFileOrFolder again");
		}
	  }
	}

The MoveThisFile method relocates a file to another area of the file system. It must be supplied with the name of the file to be moved and the new path to the file.

It uses the Move method to move the specified file to the new location.

protected void MoveThisFile(string TheFileName, string NewPath)
{
  try
  {
    Console.WriteLine("\nFile move:");
    Console.WriteLine("--------------");
    string Query = "Are you sure you want to move\n" + TheFileName + " to " + NewPath + "? ";

    Console.WriteLine(Query + "\nEnter 1 for Yes or 0 for No ");
    //parse what the user has entered
    int index = Int32.Parse(Console.ReadLine());

    //Delete if user enters 1 for Yes
    if (index == 1)
    {

      File.Move(TheFileName,NewPath);
      Console.WriteLine(TheFileName
     }
  }
}

The CopyThisFile method creates a duplicate of a file. You must supply the name of the file and specify where the duplicate is to be placed.

This uses the File.Copy method, which is part of the File class.

protected void CopyThisFile(string TheFileName, string NewPath)
{
  try
  {
    Console.WriteLine("\nFile copy:");
    Console.WriteLine("--------------");
    string Query = "Are you sure you want to copy\n" + TheFileName + " to " + NewPath + "? ";

    Console.WriteLine(Query + "\nEnter 1 for Yes or 0 for No ");
    //parse what the user has entered
    int index = Int32.Parse(Console.ReadLine());


    //Delete if user enters 1 for Yes
    if (index == 1)
    {
      File.Copy(TheFileName,NewPath);

      Console.WriteLine(TheFileName + " has been copied to " + NewPath);
     }
  }
}

The Main method of the program creates instances of the FilesFolders class and calls the CreateThisFile, MoveThisFile, CopyThisFile, and MoveThisFile methods on the new instances.

These methods must be supplied with the path to the file that is to be worked on and the location to which the file should be copied or moved for the MoveThisFile and the CopyThisFile methods.

static void Main(string[] args)
{

    FilesFolders CreateFile = new FilesFolders();
    CreateFile.CreateThisFile("C:/DotNet/test1.txt");


    FilesFolders MoveFile = new FilesFolders();
    MoveFile.MoveThisFile("C:/DotNet/test2.txt", "C:/Temp/Test.txt");


    FilesFolders CopyFile = new FilesFolders();
    CopyFile.CopyThisFile("C:/temp/Test.txt", "C:/DotNet/test2.txt");


    FilesFolders DeleteFile = new FilesFolders();
    DeleteFile.DeleteThisFile("C:/Temp/Test.txt");


    Console.ReadLine();

}

The displayed code shows the output from copying and deleting a file.

Thanks and Have Fun!!!!!

Page copy protected against web site content infringement by Copyscape

About the Author

Naimishforu
Full Name: Naimish Pandya
Member Level: Bronze
Member Status: Member,MVP
Member Since: 1/22/2011 7:38:35 AM
Country: India
Thanks, Naimish http://dotnetinterview.zxq.net/ http://naimishpandya.blogspot.in/
http://naimishpandya.blogspot.in/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)