Moving, Copying, and Deleting Files C# Help

As mentioned, moving and deleting files or folders is done by the MoveTo() and Delete () methods of the Filelnfo and Directorylnfo classes. The equivalent methods on the File and Directory classes
are Move() and Delete ( ).

The Filelnfo and File classes also implement the methods copyTo () and Copy ( ), respectively. However, no methods exist to copy complete folders – you need to do that by copying each file in the folder.

Using all of these methods is quite intuitive – you can find detailed descriptions in the SDK documentation. This section illustrates their use for the particular cases of calling the static Move( ), Copy ( ), and Delete () methods on the File class. To do this, you will build on the previous FileProperties example and call its iteration  filePropertiesAndMovernent.

This example will have the extra feature that whenever the  properties of a file are displayed, the application gives you the option of deleting that file or moving or copying the file to another location.

Example: FilepropertiesAndMovement

Image

As you can see, FilePropertiesAndMovement is similar in appearance to FileProperties, except for the group of three buttons and a text box at the bottom of the window.

These controls are enabled only when the example is actually displaying the properties of a file; at all other times, they are disabled.

The existing controls are also squashed up a bit to stop the main form from getting too big.

When the properties of a selected file are displayed, FilePropertiesAndMovernent automatically places the full path name of that file in the bottom text box for the user to edit.

Users can then click any of the buttons to perform the appropriate operation.

When they do, a message box is displayed that confirms the action
taken by the user.

When the user clicks the Yes button, the action will be initiated.

There are some actions in the form that the user can take that will then cause the display to be incorrect.

For instance, if the user moves or deletes a file, you obviously cannot continue to display the contents of that file in the same location.

In addition, if you change the name of a file in the same folder, your display will also be out of date.

In these cases, FilePropertiesAndMovernent resets its controls to display only the folder where the file resides after the file operation.

Image

Looking at the Code for FileProperties AndMovement

To code this process, you need to add the relevant controls, as well as their event handlers, to the code for the FileProperties example.

The new controls are given the names buttonDelete, buttonCopyTo, buttonMoveTo, and textBoxNewPath.

First, look at the event handler that is called when the user clicks the Delete button:

protected void OnDeleteButtonClick(object sender, EventArgs e)
{
try
{
string fileP~th = Path. Combine (currentFolderPath,
textBoxFileName.Text);
string query = “Really delete the file\n” + filePath + “?”;
if (MessageBox.Show(query,
“Delete File?”, MessageBoxButtons.YesNo) == DialogResult.Yes)
File.Delete(filePath) ;
~~ DisplayFolderList(currentFolderPath);
)
catch(Exception ex)
{
MessageBox.Showj”Unable to delete file. The following exception”
. +” occurred:\n” + eX.Message, “Failed”);

}

}

The code for this method is contained in a try block because of the obvious risk of an exception being thrown if, for example, you don’t have permission to delete the file, or the file is moved by another process after it has)feen displayed but before the user presses the Delete button. You construct the path of the file to be ,sleleted from the Current Parent Path field, which contains the path of the parent folder, and the text in the textBoxFileName text box.which contains the name of he file.

The methods to move and copy the file are structured in a very similar manner:

protected void OnMoveButtonClick(object sender, EventArgs e) ,{ .
try
{
string filePath = Path. Combine (currentFolderPath,
textBoxFileName.Text)~
query = “Really move the file\n” + filePath + “\nto ”
I + textBoxNewPath.Text + “?”; /
if (MessageBox.Show(query,
‘Move File?’, Mes.ageBoxButtons.YesNo) Dia1ogResu1t.Yes)
Fi1e.Move(fi1ePath, textBoxNewPath.Text);
Disp1ayFo1derLi.t(currentFo1derPath);
}
catch(Exception ex)
(
Me.sageBox.Show(‘Unab1e to move file. The following exception’
+ ‘ occurred:\n’ + ex.Messag., ‘Failed’);
.}
protected void onCopyButtonClick(object sender, EventArgs e)
{
try
(
string filePath = Path.Combine (currentFolderPath,
textBoxFileName.Text);
string query = ‘Really copy the file\n’ + filePath + ‘\nto ‘
+ textBoxNewPath.Text + ‘?’;
if (MessageBox.Show(query,
‘Copy File?’, Messa~eBoxButtons.YeSNo) == DialogResult.Yes)
File.Copy(filePath, textBoxNewPath.Text);
DisplayFolderList(currentFolderPath);
} -.
cat~(Exception ex)
(
MessageBox.Show(‘Unable to copy file. The following exception’
+ ‘ occurred:\n’ + ex.Message, ‘Failed’);
}

You are not quite done yet. You also need to make sure that the new buttons and text box are enabled and disabled at the appropriate times. To enable them when you are displaying the contents of a file, you add the following code to DisplayFileinfo ():

protected void DisplayFileinfo(string fileFullName)
(
Fileinfo theFile = new Fileinfo(fileFullName);
if (Ith.File.Exists)
(
throw new FileNotFoundException(‘Fi1e not found: ‘ + fileFullName);

textBoxFileName.Text  theFile.Name;
tex :oxCreationTime.Text • theFile.CreationTime.ToLongTimeString();
textBoxLastAccessTime.Text ; theFile.LastAccessTime.ToLongDateString();
textBoxLastWriteTime.Text·: theFile.LastWriteTime.ToLongDateString();
~extBoxFileSize.Text • theFile.Length.ToString() + ‘ bytes’;

II enable move, copy, delete buttons
textBoxNewPath.Text = theFile.FullName;
textBoxNewPath.Enabled = true;
buttonCopyTo.Enabled true;
buttonDelete.£nabled true;
buttonMoveTo.Enabled true;

throw new DirectoryNotFoundException(‘Folder not found: ‘ + folderFullName);
You also need to make one change to DisplayFolderList:
protected void DisplayFolderList(string folderFuIIName)
{
Directorylnfo theFolder = new Directorylnfo(folderFuIIName);
if (!theFolder.Exists)
{
II list all subfolders in folder
foreach(Directorylnfo nextFolder in theFolder.GetDirectories())
listBoxFolders.ltems.Add(NextFolder.Name);
ClearAllFields();
DisableMoveFeatures();
textBoxFolder.Text = theFolder.FullName;
currentFolderPath = ~heFolder.FullName;
..> II list all files in folder
foreach(Filelnfo nextFile in theFolder.GetFiles())
listBoxFiles.ltems.Add(NextFile.Name);
DisableMoveFeatures is a small utility function that disables the new controls:
void DisableMoveFeatures()
{
textBoxNewPath. Text =’ “;
textBoy~ewPath.Enabled = false’
buttonCopyTo.Enabled false;
buttonDelete.Enabled false;
buttonMoveTo.Enabled false;
You also need to add extra code to ClearAllFields () to clear Ute extra text box:
protected void ClearAllFields()
{
listBoxFolders.ltems.Clear();
listBoxFiles.ltems.Clear() ;
textBoxFolder.Text = “; textBoxFileName.Text = “;
textBoxCreationTime.Text = “;

textBoxLastAccessTime.Text = “”; textBoxLastWriteTime.Text = “”; textBoxFileSize.Text = “”; textBoxNewPath.Text = “”;

}
The next section takes a look at reading and writing to files.

Reading and Writing to Flies

Reading and writing to files is in principle very simple; however, it is not done through the DirectoryInfo or FileInfo objects. Instead, using the .NET Framework 3.5, you can do it through the File object.

Later in this chapter, you see how to accomplish this using a number of other classes that represent a generic concept called a stream.

Before the .NETFramework 2.0, it took a bit of wrangling to read and write to files.

It was possible using the available classes from the framework, but it was not that straightforward.

The .NETFramework 2.0 has expanded the File class to make it as simple as just one line of code to read or write to a file.

This same functionality is also available in version 3.5 of the .NETFramework.

Reading a File

For an example of reading a file, create a Windows Font;lapplication that contains a regular text box, a button, and a multiline text box.

In the end, your form should appear something like

Image

The idea of this form is that the end user will enter in the path of a specific file in the first text box and click the Read button.

From here, the application will read the specified file and display the file’s contents in the multiline text box.

This is illustrated in the following code example:

using System;
using System.IO;
using System.Windows,Forms;
namespace ReadingFiles
{
public partial class Forml Form
{
public Forml ()
{
InitializeComponent();
private void buttonl_Click(object sender, EventArgs e)
{
textBox2.Text = File.ReadAIIText(textBoxl.Text);

}

}

}

In building this example, the first step is to add the using statement.to bring in the System. 10 namespace.

From there, simply use the buttonl_Click event for the Send button on the form to populate the text box with what comes back from the file.

You can now access the file’s contents by using the File.

The ReadAll Text () method. As you can see, you can read files with a single statement.

The ReadAIltext () method opens the specified file, reads the contents, and then closes the file.

The return value of the ReadAII Text () method is a string array containing the entire contents of the file specified.

The result would be something similar to what is shown.

Image

The File. ReadAll Text () signature shown in the preceding example is of the following construction:
File.ReadAllText(FilePath);
The other option is to also specify the encoding of the file being read:
File. ReadAllText (FilePath, Encoding);
Using this signature allows you to specify the encoding to use when opening and reading the contents of the file.

Therefore, this means that you could do something like the following:
File.ReadAllText(textBoxl.Text, Encoding.ASCII);

Some of the other options for opening and working with files include using the R.eadAllBytes ( ) and the ReadAllLines () methods.

The ReadAllBytes () method allows you to open a binary file and
read the contents into a byte array.

The ReadAll Text () method shown earlier gives you the entire contents of the specified file in a single string array instance.

This might not be something that you are interested in.

You might instead be interested in working with what comes back from the file in a line-by-line fashion.

In this case, you will want to use the ReadAllLines ( ) method because it will allow for this kind of functionality.

Writing to a File

Besides making reading from files an extremely simple process under the .NET Framework umbrella, the base class library has made writing to files just as easy.

Just as the base class library (BCL) gives you the ReadAll Text ( ), ReadAllLines ( ) , and ReadAllBytes () methods to read files in a few different ways, it gives you the Wri teAll Text ( ), WriteAllBytes ( ), and wri teAllLines ( ) methods to write files.

For an example of how to write to a file use the same Windows Form application, but use the multiline text box in the form to input data into a file.

The code for the but tonl_Click event handler should appear as shown here:

private void buttonl_Click(object sender, EventArgs e)
( . File. Wri teAll Text (t.extBoxl. Text, textBox2. Text) ;
)

Build and start the form, type C:\Testing.txt in the first text box, type some random content in the second text box, and then click the button.

Nothing will happen visually, but if you look in your root C drive, you will see the Testing.txt file with the content you specified.

The WriteAlIText () method went to the specified location, created a new text file, and provided the specified contents to the file before saving and closing the file.

Not bad for just one line of code!

If you run the application again, and specify the same file (testing.txt) with some new content, pressing the button again will cause the application perform the same task.

This time though, the new content is not added to the previous content you specified — instead the new content completely
overrides the previous content.

In fact, WriteALLText (), Write all bytes () , and WriteAllLines ()
all override any previous files, so you must be careful when using these methods.

The WriteAllText () method in the previous example uses the following signature:

Flle.WriteAllText/filepath,Contents

you can also specify the encoding of the new file:

File.writeAllText(Filepath, contents, Encoding)

data source makes it easier to swap data sources. Stream objects themselves contain a lot of generic code that concerns the movement of data between outside sources and variables in your code.

By keeping this code separate from any concept of a particular data source, you make it easier for this code to be reused (through inheritance) in different circumstances.

For example, the StringReader and StringWriter classes are part of the same inheritance tree as two classes that you will be using later on to read and write text files.

The classes will almost certainly share it substantial amount of code behind the scenes.

illustrates the actual hierarchy of stream-related classes in the System.

IO namespace.

As far as reading and writing files, the Classes that concern us most are:

¤ FileStream-This class is intended for reading and writing binary data in a binary file.

However, you can also use it to read from or write to any file.

¤ StreamReader and StreamWriter — These classes are designed specifically for reading from and writing to text files.

Image

You might also find the BinaryReadel”and BinaryWri ter classes useful, although they are not used in the examples here.

These classes do not actually implement streams themselves, but they are able to provide wrappers around other stream objects.

BinaryReader and BinaryWri ter provide extra formatting of binary data, which allows you to directly read or write the contents of C# variables to or from the relevant stream.

Think of the BinaryReader and BinaryWriter as sitting between the stream and your code, providing extra formatting.

Image

The difference between using these classes and directly using the underlying stream objects is that a basic stream works in bytes.

For example, suppose that as part of the process of saving some document you want to write the contents of a variable of type long to a binary file.

Each long occupies 8 bytes, and if you used an ordinary binary stream, you would have to explicitly write each of those 8 bytes of
memory.

In C# code, that would mean you would have to perform some bitwise operations to extract each of those 8bytes from the long value, Using a BinaryWriter instance, you can encapsulate the
entire operation in an overload of the BinaryWriter.

Write () method, which takes a long as a parameter, and which will place those 8 bytes into the stream (and if the stream is directed to a file, into the file).

A corresponding BinaryReader .Read () method will extract 8 bytes from the stream and recover the value of the long.

For more information on the BinaryReader and BinaryWriter classes, refer to the SDK documentation.

Posted on October 28, 2015 in Manipulating Files and the Registry

Share the Story

Back to Top