Manipulating Files in C#
Posted On September 22, 2007 by Priyadarshan Roy filed under
Microsoft has provided very intuitive object models for file manipulation tasks. For file system operations we will be using System. IO namespace. Also we can use the FileInfo and DirectoryInfo classes, which are within the System.IO, namespace for creating and moving files.
For Example to create a new file we will use the following syntax.
FileInfo myFile = new Fileinfo(@”c:\Readme.txt”);
MyFile.CopyTo(@”D:\Readme.txt”);
Has the same effect as
FileInfo myFile = new Fileinfo(@”c:\Readme.txt”, @”D:\Readme.txt”);
The first code will take slightly longe to execute, because of the need to instantiate a FileInfo object, MyFile. The second example there is no need to instantiate an object to copy the file.
We can instantiate DirectoryInfo or FileInfo class by passing to the constructor a string containing the path to the corresponding file system. We have just seen the process for a file. For a folder the code looks similar.
DirectoryInfo = myFolder = new DirectoryInfo(@c:\windows”);
If the path represents an object does not exist, an exception will not be thrown at construction, but will instead be thrown the fist time that you call a method that actually requires the corresponding file system object to be there. We can find out whether the object exists and is of the appropriate type by checking the Exists property, which is implemented by both of these classes.
FileInfo test = new FileInfo(@c:\Windows);
Console.WriteLine(test.Exists.ToString());
We can find you’re the Properties and methods of the FileInfo or SystemInfo class.
Name | Description |
| Length(FileInfo only) | The size of the file in bytes |
| Root(DirectoryInfo only) | The root portition of the Path |
| Name | Name of the file or folder |
| LastWriteTime | Time file or folder was last modified |
| LastAccessTime | Time file or folder was last accessed |
| FullName | Full pathname of the file or folder |
| Extension | Extension of the file |
| Parent(DirectoryInfo only) | The Parent directory of a specified subdirectory |
| DirectoruName | Full pathname of the containing folder |
| CreationTime | Time file or folder was created |
We can also perform actions on the file system object using the following methods.
Name | Use |
| Create() | Creates a folder or emptyfile of the given name. |
| Delete() | Deletes the file or folder. For the folders there is an option for the Delete to be recursive. |
| CopyTo() | (FileInfo only) Copies the file. Note that there is no copy method for folders. |
| MoveTo() | Moves and/or renames the file or folder |
| GetDirectories() | (DirectoryInfo only) Returns an array of DirectoryInfo objects representing all folders contained in this folder. |
| Getfiles() | (DirectoryInfo only) Returns an array of FileInfo objects representing all files contained in this folder. |
| GetFileSystemInfos() | (DirectoryInfo only) Returns FileInfo and DirectoryInfo objects representing all objects contained in this folder, as an array of FileSystemInfo references. |
In C# we can display creation time, last access time and last write time are all writable.
// To display the creation time of a file
//then changes it and displays it again
FileInfo test = new FileInfo(@”C:\readme.txt”);
Console.WriteLine(test.Exists.ToString());
Console.WriteLine(test.CreationTime.ToString());
Test.CreationTime – new DateTime(2006, 1,1, 11, 15, 0);
Console.writeLine(test.CreateTime.ToString());
When you run this program you will see the results.
We can manually modify these properties might seem strange at first, but it can be quite useful. For example, if we have a program that effectively modifies a file by simply reading it in, deleting it and creating a new file with the new concepts, we did not probably want to modify the creation date to match the original creation date of the old file.
Path class
The path class is not a class that you would instantiate. Rather, it exposes some static methods that make operations on pathnames easier. For example if we want to display the full pathname for a file, ReadMe.txt in the folder C:\windows. You can find the path to the file using the following code.
Console.WriteLine(path.Combine(@”C:\windows”, “ReadMe.txt”));
Now we will create a small file browser to browse directories and view the properties of the files. Using this file browser you can view the creation time, last access time, last write time, and size of files.
From Visual Studio 2005 create new C# window application and add the textboxes and the list box from the toolbox to Windows form area. Rename the controls with more proper names. That is textBoxInput, textBoxFolder, buttonDisplay, buttonUp, listBoxFiles, listBoxFolders, textBoxFileName, testBoxCreationTime, textboxAccessTime, textBoxLastWriteTime and textBoxFileSize.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.IO;
using System.Drawing;
Now we need to add the event handler for the user-generated events. Before we add the code for the event handlers we need to clear the contents of all the controls. This method is very simple.
protected void clearfields()
{
listBoxFolders.Items.Clear();
listBoxFiles.Items.Clear();
txtBoxFolder.Text = "";
txtBoxFileName.Text = "";
txtBoxCreationTime.Text = "";
txtBoxFileSize.Text = "";
txtBoxLastAccessTime.Text = "";
txtBoxLastWriteTime.Text = "";
}
Now we will define a method, DisplayFileInformation(), that handles the process of displaying the information for a given file in the text boxes. This method takes one parameter, the full pathname of the file as a String, and it works by creating a FileInfo object based on this path.
protected void DisplayFileInformation(string fileFullName)
{
FileInfo theFile = new FileInfo(fileFullName);
if (!theFile.Exists)
throw new FileNotFoundException("File not found: " + fileFullName);
txtBoxFileName.Text = theFile.Name;
txtBoxCreationTime.Text = theFile.CreationTime.ToLongTimeString();
txtBoxLastAccessTime.Text = theFile.LastAccessTime.ToLongDateString();
txtBoxLastWriteTime.Text = theFile.LastWriteTime.ToLongDateString();
txtBoxFileSize.Text = theFile.Length.ToString() + " bytes";
}
We have to take the precaution of throwing an exception if there are any problems locating a file at the specified location. The Exception itself will be handled in the calling routine. Now we define a method, displayfolderlist(), which will display the content of the given folder in the two list boxes. Full path name is passed as a parameter for this method.
protected void DisplayFolderList(string folderFullName)
{
DirectoryInfo theFolder = new DirectoryInfo(folderFullName);
if (!theFolder.Exists)
throw new DirectoryNotFoundException("Folder not found: "
+ folderFullName);
clearfields();
txtBoxFolder.Text = theFolder.FullName;
currentFolderPath = theFolder.FullName;
// list all subfolders in a give folder
foreach (DirectoryInfo nextFolder in theFolder.GetDirectories())
listBoxFolders.Items.Add(nextFolder.Name);
// list all files in the perticular folder
foreach (FileInfo nextFile in theFolder.GetFiles())
listBoxFiles.Items.Add(nextFile.Name);
}
We will write the code for the event handlers. Add the following code in the OnDisplayButtonClick event.
protected void OnDisplayButtonClick(object sender, EventArgs e)
{
try
{
string folderPath = txtBoxInput.Text;
DirectoryInfo theFolder = new DirectoryInfo(folderPath);
if (theFolder.Exists)
{
DisplayFolderList(theFolder.FullName);
return;
}
FileInfo theFile = new FileInfo(folderPath);
if (theFile.Exists)
{
DisplayFolderList(theFile.Directory.FullName);
int index = listBoxFiles.Items.IndexOf(theFile.Name);
listBoxFiles.SetSelected(index, true);
return;
}
throw new FileNotFoundException("There is no file or folder with "
+ "this name: " + txtBoxInput.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In the above code, we establish if the supplied text represents a folder or file by instantiating DirectoryInfo and FileInfo instances and examining the Exists property of each object. If nither exists, then we throw an exception. If it’s a file, you need to populate the list boxes and sort out the text boxes that dislay the file properties. If it’s a folder, you call displayfolderlist().
The following event handler is called when an item in the File list box is selected bu the user. It simply constructs the full pathname of the selected file and passes this to the DirectoryFileInfo() method as shown below.
protected void OnListBoxFilesSelected(object sender, EventArgs e)
{
try
{
string selectedString = listBoxFiles.SelectedItem.ToString();
string fullFileName = Path.Combine(currentFolderPath, selectedString);
DisplayFileInformation(fullFileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The event handler for the selection of a folder in the Folders listbox is implemented in a same way, except that in this case you call DisplayFolderList() to update the content of the list boxes.
protected void OnListBoxFoldersSelected(object sender, EventArgs e)
{
try
{
string selectedString = listBoxFolders.SelectedItem.ToString();
string fullPathName = Path.Combine(currentFolderPath, selectedString);
DisplayFolderList(fullPathName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Finally we will write the code for the Up button selected. Add the following code when the OnButtonClick.
protected void OnUpButtonClick(object sender, EventArgs e)
{
try
{
string folderPath = new FileInfo(currentFolderPath).DirectoryName;
DisplayFolderList(folderPath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In the above code DisplayFolderList() must also be called, except that this time you need to obtain the parent of the folder cuttently being displayed. This is done with the FileInfo.DirectoryName property, which will return the parent folder path.
By modifing the file browser form you can also delete, move or copy file from one location to other location. You can also read and write files.
The author is studying MCA at Ignou Open Univercity HyderaBad. He can be reached at: deepak_kumar123@rediff.co.in
