A Look at C# File and FileInfo Classes

When you think about creating files programmatically in C# you have the option of using the File class or the FileInfo class. In this article, we are going to create, copy and move files using those classes. This is the second article in a multi-part series.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 15
January 30, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

You need to read my earlier article, "A Look at C# Directory and DirectoryInfo Classes," before you read this one because we are going to use the concepts explained in that article here. You need VS.NET 2003 installed on your machine in order to run the code examples. Before you run the examples, you may need to change the drive letter because I'm using the drive letter F (actually, this is an empty drive on my machine).

We discuss the Path class first. Let's get to work.

Understanding the Path Class

As you already know, a path is a string that tells you where your file or directory is located. So F:MyFolderMyFolder1help.txt is a path to the file help.txt which tells us that the file exists in the folder MyFolder1, which exists in the MyFolder directory. Different platforms use different separator characters, but we can use the Path class to build path names without worrying about this issue.

The Path class contains only static members such as the Path.Combine() method, which you use to build the path name that's platform-specific. The Path class provides us with other useful members that are illustrated by the following example.

using System;
using System.IO;

namespace IOProject
{
  class Class1
  {
    static void Main(string[] args)
    {
      Console.WriteLine("The Path Separator Character = {0}",
      Path.DirectorySeparatorChar);
      Console.WriteLine("The Path Alternative Separator
Character = {0}",
      Path.AltDirectorySeparatorChar);
      Console.WriteLine("The Path Separator = {0}",
Path.PathSeparator);
      Console.WriteLine("Combining the string " F:MyFolder "
and " + "" MyFolder1 " using Path.Combine()");
      Console.WriteLine(Path.Combine("F:MyFolder",
"MyFolder1"));
      Console.ReadLine();
    }
  }
}

To run the above code create a new VS.NET Console Application Project, replace the Class1.cs auto-generated code with the above code, then run it.

The first line in the Main() method prints out the value of the Property Path.DirectorySeparatorChar, the "" character, which is used on the Windows operating system to separate the names of folders and files to build the path; the value of this Property on Unix is "/". The next line prints out the value of the Property Path.AltDirectorySeparatorChar which is the "/" character on Windows and "" in the Unix Operating System to separate the names of folders and files  to build the path. The Path.PathSeparator property returns the path separator character ;. The Path.Combine() method combines two strings and forms one path name. So the method call Path.Combine("F:MyFolder", "MyFolder1") returns F:MyFolderMyFolder1. There are some other members of the Path class but we will not discuss them. Instead, we are going to begin our discussion of the FileInfo and File Classes.

The File and FileInfo Classes

You may recall from my earlier article that the Directory Class contains only static methods, and we should use this class only when we need to perform one or two operations on a folder. On the other hand, the DirectoryInfo class is used to create an instance that's associated with a specific folder, and we use an instance of this class when we need to perform many operations on the folder.

The same rule applies to the File and the FileInfo classes. We use the static methods of the File Class to perform one operation on the file, and use an instance of the FileInfo class if we are going to perform many operations on the file. So it isn't worth the overhead of creating a FileInfo object just to perform one operation such as checking to see whether a file exists in a directory.

The File class contains many useful methods such as Create(), Move(), Copy(), Delete() and Exists. These methods are self explanatory. There are also methods that return information about the file itself, such as GetAttributes(), SetAttributes, GetCreationTime(), SetCreationTime(), GetLastAccessTime(), SetLastAccessTime(), GetLastWriteTime() and SetLastWriteTime().

The File class contains methods that return stream-based objects such as Create(), OpenText(), AppendText(), Open(), OpenRead(), OpenText() and OpenWrite(). You don't have to worry because we are going to discuss stream-based classes in a separate article. In the meantime we are going to focus on Creating, Moving and Copying.

The methods of the File and FileInfo classes are similar, but they differ in that the methods of the File class are static, so you need to pass more parameters than you would for the methods of the FileInfo instance. You need to do this because it operates on a specific file; for example, the FileInfo.CopyTo() method takes one parameter for the destination path that's used to copy the file, whereas the File.Copy() method takes two parameters for the source path and the destination path. Now let's look at an example of creating files.

using System;
using System.IO;

namespace IOProject
{
  class Class1
  {
    static void Main(string[] args)
    {
      try
      {
        Console.WriteLine("Creating the Directory");
        DirectoryInfo dirInfo = new DirectoryInfo(
        Path.Combine("F:" +
Path.DirectorySeparatorChar,"MyFolder"));
        if(dirInfo.Exists == false)
        {
          dirInfo.Create();
          Console.WriteLine("The folder {0} has been created.",
dirInfo.FullName);
        }

        Console.WriteLine("Creating 3 subdirectories");
        for(int i = 1; i < 4; i++)
        {
          dirInfo.CreateSubdirectory("MyFolder" + i);
        }

        Console.WriteLine("Creating 3 files in the first
subdirectory");
        for(int i = 1; i < 4; i++)
        {
          FileInfo aFile = new FileInfo(@"F:MyFolderMyFolder1"
+ "File" + i + ".txt");
          aFile.Create();
          Console.WriteLine("The file {0} has been created at
{1} and the file size = {2}",
          aFile.FullName, aFile.CreationTime, aFile.Length);
          Console.WriteLine();
        }
      }
      catch(IOException ex)
      {
        Console.WriteLine(ex.Message);
      }
      finally
      {
        Console.ReadLine();
      }
    }
  }
}

Copy the above code, paste it in place of the auto-generated code of Class1.cs in your Console Application Project, then press F5 to run it.

The second line in the try block of the Main() method creates a DirectoryInfo object called dirInfo. Then the if statement checks if the folder already exists. Since it doesn't exist, the Exists property returns false, causing the if statement to evaluate to true and to create the folder using the Create() method.

Then the for statement creates three subdirectories using the method dirInfo.CreateSubdirectory(). Now we have the folder F:MyFolder and three subdirectories inside it, namely MyFolder1, MyFolder2 and MyFolder3. The second for statement creates three files in the directory MyFolder1. We first create the FileInfo object and pass the path to the file; because the file doesn't exist, the aFile.Create() method creates it. Note that if the file already exists, no exception is thrown.

We have used a FileInfo object because we need to retrieve some information on the file like FullName, CreationTime and Length (the size of the file). It is then printed out using the Console.WriteLine() method. The following screen shot shows that the files have been created.

Note that we have used concatenation in order to name the files File1.txt, File2.txt and File3.txt. Let's look at another example.

Moving the files to another directory

The following code moves the files from MyFolder1 directory to MyFolder2. So let's take a look at it.

using System;
using System.IO;

namespace IOProject
{
  class Class1
  {
    static void Main(string[] args)
    {
      try
      {
        DirectoryInfo dirInfo = new DirectoryInfo
(@"F:MyFolderMyFolder1");
        DirectoryInfo dirInfo2 = new DirectoryInfo
(@"F:MyFolderMyFolder2");
        Console.WriteLine("Listing the files in MyFolder2:");
        FileInfo[] myFolder2Files = dirInfo2.GetFiles();
        if(myFolder2Files.Length > 0)
        {
          foreach(FileInfo aFile in myFolder2Files)
          {
            Console.WriteLine(aFile.FullName);
          }
        }
        else
        {
          Console.WriteLine("There are no files
MyFolder2...n");
        }
        Console.WriteLine("Moving the files from MyFolder1 to
MyFolder2");
        FileInfo[] myFolder1Files = dirInfo.GetFiles();
        foreach(FileInfo aFile in myFolder1Files)
        {
          if(File.Exists(@"F:MyFolderMyFolder2" + aFile.Name))
          {
            File.Delete(@"F:MyFolderMyFolder2" + aFile.Name);
          }
          aFile.MoveTo(@"F:MyFolderMyFolder2" + aFile.Name);
        }
        Console.WriteLine("The files have been moved to
MyFolder2 directory");
        Console.WriteLine("Listing the files in MyFolder2:");
        myFolder2Files = dirInfo2.GetFiles();
        if(myFolder2Files.Length > 0)
        {
          foreach(FileInfo aFile in myFolder2Files)
          {
            Console.WriteLine(aFile.FullName);
          }
        }
        else
        {
          Console.WriteLine("There are no files in the directory
MyFolder2");
        }
      }
      catch(IOException ex)
      {
        Console.WriteLine(ex.Message);
      }
      finally
      {
        Console.ReadLine();
      }
     }
  }
}

Run the above code and you will get the following screen shot. Don't forget to modify the drive letter.

Now the files have been moved to the MyFolder2 directory.

Let's walk through the code. The first two statements of the try block in the Main() method create two DirectoryInfo objects that correspond to the folders MyFolder1 and MyFolder2. The next thing we do is list the files in the MyFolder2 directory (which has no files, but you may have created some files there) by creating a FileInfo array and assigning it a return array value. We call the method dirInfo2.GetFiles(), then we use an if statement to check whether myFolder2Files.Length > 0 and if so, we list the files using a foreach statement. If there are no files, we write that to the Console.

Now we need to move the files from MyFolder1 to MyFolder2. We do that using the FileInfo.MoveTo() instance method that accepts a destination path as a string value. Because we need to move more than one file we use the FileInfo.MoveTo() method inside a foreach statement.

First, we get the files of the MyFolder1 directory using the dirInfo.GetFiles() method and assign it to a FileInfo array, then inside the foreach structure we check to see whether the file already exists in the MyFolder2 directory. If it exists, we delete it using the static method Delete() of the File class.

You may want to create a FileInfo object and then call the Delete() method, but as we said before, this is just one operation that we are going to do on that file (the file that we want to delete in the MyFolder2 directory), so there is no need to create an object. It's sufficient to use the File.Delete() static method to delete the file.

The method MoveTo() moves the file to MyFolder2 with the same file name. Note that you can specify a new name for the file with the MoveTo() method.

We again use the GetFiles() method of the object dirInfo2 to get its files as an array of FileInfo objects. We then assign this array to myFolder2Files variable, and we use it in the foreach statement to list the files. Let's do one more thing.

Copying the files to MyFolder3

For this example we need to write and save the following text into the files of the MyFolder2 directory using Notepad:

The files contains some text

Create a file named File1.txt in the MyFolder3 directory but leave it empty. Now let's move to the code.

using System;
using System.IO;

namespace IOProject
{
  class Class1
  {
    static void Main(string[] args)
    {
      try
      {
        DirectoryInfo dirInfo2 = new DirectoryInfo
(@"F:MyFolderMyFolder2");
        DirectoryInfo dirInfo3 = new DirectoryInfo
(@"F:MyFolderMyFolder3");
        Console.WriteLine("Listing the files in MyFolder2:");
FileInfo[] myFolder2Files = dirInfo2.GetFiles();
        if(myFolder2Files.Length > 0)
        {
          foreach(FileInfo aFile in myFolder2Files)
          {
            Console.WriteLine("File Name: {0}, Size:
{1}",aFile.FullName, aFile.Length);
          }
          Console.WriteLine("n");
        }
        else
        {
          Console.WriteLine("There are no files
MyFolder2...n");
        }

        Console.WriteLine("Listing the files in MyFolder3:");
        FileInfo[] myFolder3Files = dirInfo3.GetFiles();
        if(myFolder3Files.Length > 0)
        {
          foreach(FileInfo aFile in myFolder3Files)
          {
            Console.WriteLine("File Name: {0}, Size:
{1}",aFile.FullName,aFile.Length);
          }
          Console.WriteLine("n");
        }
        else
        {
          Console.WriteLine("There are no files
MyFolder3...n");
        }
        Console.WriteLine("Copying the files from MyFolder2 to
MyFolder3");

        foreach(FileInfo aFile in myFolder2Files)
        { 
          aFile.CopyTo(@"F:MyFolderMyFolder3" + aFile.Name,
true);
        }
        Console.WriteLine("The files have been copied to
MyFolder3 directory"); 
        Console.WriteLine("Listing the files in MyFolder3:");
        myFolder3Files = dirInfo3.GetFiles();
        if(myFolder3Files.Length > 0)
        {
          foreach(FileInfo aFile in myFolder3Files)
          {
            Console.WriteLine("File Name: {0}, Size:
{1}",aFile.FullName,aFile.Length);
          }
        }
        else
        {
        Console.WriteLine("There are no files in the directory
MyFolder3");
        }
      }
      catch(IOException ex)
      {
        Console.WriteLine(ex.Message);
      }
      finally
      {
        Console.ReadLine();
      }
    }
  }
}

As usual, replace the above code with the code of the Class1.cs then press F5 to run the application.

Here are the files in MyFolder3

The code has nothing new except the CopyTo() method, which accepts a destination path and a Boolean value that indicates whether the file overwrites an existing file with the same name or not.

Notice that we have listed the files of MyFolder2. We have found that all the files has the same size (28 Bytes) because they contain the same text. When we have listed the files in MyFolder3, we found the only file that we created (the empty file1.txt file) has a size of 0 Bytes. After the copying operation we found that the file MyFolder3file1.txt has the same size as the other files (28 Bytes) because it has been overwritten by the CopyTo() method.

In my next article I'm going to show you how to write to and read from files using stream-based classes.

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials