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:

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:

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 ():

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.

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:

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.