Managing Files in C#

If you found this article, that means I don’t need to introduce the purpose of computer files. As a programmer, you’ll find that managing files is required almost everywhere regardless of the project. Working with files is really important because they store data. In this tutorial, we’re going to learn how we can copy, move, rename, delete, and grab the file attributes of a file, as the title suggests, in C#.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 8
March 11, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Throughout this tutorial, I will assume that the reader is familiar with the syntax of C# and, therefore, will only explain in detail what each "new" function does and how to use them appropriately. Our project will use file managing functions as examples so that we will have some "real-world" proof of what they do as an end-result.

The style of this article will be intuitive and pretty straightforward. I'm going to paste code snippets from the project and explain what these blocks of code mean. If it's a function, then I'll analyze its parameters, arguments, and so forth. Following along shouldn't be hard at all because we won't adopt a fast pace.

We are going to finish this tutorial by attaching the archived source of this project. You may download it, see how it works, fiddle with it, and find out what you have missed or done wrong if you were struggling to make your application run. To clarify any confusion, I'll show you a screen shot at the beginning that points out the way I named the form components. This way, we can both work accordingly.

This being said, I think we should move on. Launch Visual Studio and turn the page.

The Foundations

Now that you've started Visual Studio, let's create our new project. It's quite straightforward that we opt for a new C# Windows Application. Once that's created, check out the way I've designed my form. The one and only main form is called frmMain and its sizes are the following: 415, 183. I've disabled the MaximizeBox and set its form border style to FixedSingle.



I have opted to write the entire code into the frmMain.cs, because this way we eliminate the need to have code snippets in both a separate C# code file and the form with the Windows Form Designer-generated code. All code is within one file in our case, and that's frmMain.cs. Oh, and don't forget to add two dialogs to our form: openFileDialog and saveFileDialog. This is also the way I named them.

Our project won't require any additional namespaces and/or libraries so we stick to the defaults.


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;


The name of the project is FileManager, thus the following class is created. By the way, keep in mind that I have intentionally left out the Windows Form Designer-generated code as well as the declarations of components' variables and their configurations. It's your job to configure them. Afterward, the IDE generates the code.


static class FileManager

{

[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new frmMain());

}

}


As you can see from the above block of code, the application runs the frmMain() public method. It is going to be part of a public partial class. Additionally, as soon as the form is loaded and the components are initialized, we are going to hide the "unnecessary" components from the form and resize only the menu.


public partial class frmMain : Form

{

public frmMain()

{

InitializeComponent();

}

private void frmMain_Load(object sender, EventArgs e)

{

this.txtProperties.Hide();

this.btnHide.Hide();

this.lblNewFileName.Hide();

this.txtNewFileName.Hide();

this.btnGoRename.Hide();

this.btnCancel.Hide();

this.ClientSize = new System.Drawing.Size(145, 158);

}

}


Hide() conceals the control from the user. With the help of ClientSize(), we specify the new size for our frmMain (this refers to that). Now that we have built the basics of our project, we can move on by coding the components and discussing what each of them does. Now comes the real part. Everything that you find below is part of the partial class called frmMain (that's where the Win Form Designer generated code goes also).

Copying, Moving, and Deleting

Due to the nature of our project, we need to have a source and a destination file. That's what we are going to use on almost every action during our tutorial - copy, move, etc. The destination won't be use as frequently as the source, but we still need to have it prepared. To accomplish this, we are going to create two strings, sourceFileName and destFileName. After this, we can code the dialog boxes' [OK].


private void openFileDialog_FileOk(object sender, CancelEventArgs e)

{

sourceFileName = openFileDialog.FileName;

}

private void saveFileDialog_FileOk(object sender, CancelEventArgs e)

{

destFileName = saveFileDialog.FileName;

}


You can guess what the above block of code does, right? It's intuitive. As soon as the user picks his/her source and destination files in the dialog boxes, those two variables will carry their address/path (i.e. C:Tempdatabase.txt).

Let the fun begin! Now we will code what happens when we click on btnCopy. The snippet is attached below, but first let me explain it in a nutshell. We display/run the dialog boxes because we need the source and destination paths. A quick bit of error handling is necessary because if there is a "null" or empty path, our copy method goes nuts. As soon as this is done we use System.IO.File.Copy() to copy the file. Then we notify the user with a pretty `Done with success` message box.


private void btnCopy_Click(object sender, EventArgs e)

{

sourceFileName = null;

destFileName = null;

openFileDialog.ShowDialog();

if (!System.IO.File.Exists(sourceFileName))

{

MessageBox.Show("The selected file either does not exist or you didn't pick any.");

return;

}

saveFileDialog.ShowDialog();

if (destFileName == null || destFileName == "")

{

MessageBox.Show("You didn't pick the destination path.");

return;

}

System.IO.File.Copy(sourceFileName, destFileName);

MessageBox.Show("Done with success.");

}


We do the same for btnMove, too. The only difference is that we will use the System.IO.File.Move() to accomplish the file-moving action. The rest remains the same.


private void btnMove_Click(object sender, EventArgs e)

{

sourceFileName = null;

destFileName = null;

openFileDialog.ShowDialog();

if (!System.IO.File.Exists(sourceFileName))

{

MessageBox.Show("The selected file either does not exist or you didn't pick any.");

return;

}

saveFileDialog.ShowDialog();

if (destFileName == null || destFileName == "")

{

MessageBox.Show("You didn't pick the destination path.");

return;

}

System.IO.File.Move(sourceFileName, destFileName);

MessageBox.Show("Done with success.");

}


Next is btnDelete, because it's the easiest. We will skip renaming and grabbing the file attributes for now. You will find those on the next page. Delete works based on a sourceFileName, so requiring the user to specify a destination file is silly! We will do the usual error handling and then, for convenience, we'll display a confirmation message box. The user might miss-click or your code might be buggy and then something important becomes deleted. After clicking "Yes," we delete the file.


private void btnDelete_Click(object sender, EventArgs e)

{

sourceFileName = null;

openFileDialog.FileName = null;

openFileDialog.ShowDialog();

if (!System.IO.File.Exists(sourceFileName))

{

MessageBox.Show("The selected file either does not exist or you didn't pick any.");

return;

}

if (MessageBox.Show("Are you sure? You are about to delete the following file: " + sourceFileName, "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)

{

System.IO.File.Delete(sourceFileName);

MessageBox.Show("Done with success.");

}

}


The rename and properties parts are a bit longer, but that doesn't necessarily mean they're more complex or advanced. We'll do our best to explain what each snippet does and why we opted for that type of algorithm, have no fear. Turn the page, if you're ready.

Renaming and File Attributes

It is pretty much self-explanatory that to rename a file you need the source file as well as its new name. We will accomplish the renaming action using the same approach we used while removing a file. The only difference is that we don't change the file's path, just its name. But this can also be done using System.IO.File.Move().

First, as soon as the user clicks on btnRename, we display the dialog box. Then the user picks the source file and we resize frmMain, revealing lblNewFileName, txtNewFileName, and two buttons (btnGoRename and btnCancel). The txtNewFileName field is initialized with the following text value: "type here the new name with extension."


private void btnRename_Click(object sender, EventArgs e)

{

sourceFileName = null;

openFileDialog.ShowDialog();

if (!System.IO.File.Exists(sourceFileName))

{

MessageBox.Show("The selected file either does not exist or you didn't pick any.");

return;

}

this.ClientSize = new System.Drawing.Size(415, 158);

this.lblNewFileName.Show();

this.txtNewFileName.Show();

this.btnGoRename.Show();

this.btnCancel.Show();

}


The user is required to specify the new name of the source file in the text field called txtNewFileName. We do a quick bit of error handling to eliminate the possibility of it being the said "type here the new name with extension" or null. Then we move on to actually rename the file (using remove, but not changing the destination path, just the name of the file) and then resizing the frmMain to conceal components we don't need.


private void btnGoRename_Click(object sender, EventArgs e)

{

destFileName = txtNewFileName.Text;

if (destFileName == "type here the new name with extension" || destFileName == "" || destFileName == null)

{

MessageBox.Show("You didn't pick the new file name.");

return;

}

System.IO.File.Move(sourceFileName, destFileName);

MessageBox.Show("Done with success.");

this.lblNewFileName.Hide();

this.txtNewFileName.Hide();

this.btnGoRename.Hide();

this.btnCancel.Hide();

this.ClientSize = new System.Drawing.Size(145, 158);

}


We can't forget about the btnCancel either. If the user clicked on btnRename from the main menu and the rename components are displayed, the form is resized, and all that happens; but what if s/he wants to go back to the main menu and choose Copy instead of Rename? Our btnCancel conceals every rename component, resizes frmMain to its original size, and basically everything goes back to the menu.


private void btnCancel_Click(object sender, EventArgs e)

{

this.lblNewFileName.Hide();

this.txtNewFileName.Hide();

this.btnGoRename.Hide();

this.btnCancel.Hide();

this.ClientSize = new System.Drawing.Size(145, 158);

}


There's one more thing left for us to code and implement, and that's the btnProperties. When the user clicks on this button, the dialog box is displayed and the user picks the source file. Error handling isn't forgotten. We resize frmMain and display the large txtProperties text box (that's where the attributes of the file will be reported) and the btnHidden button (this goes back to the menu resizing the form).


private void btnProperties_Click(object sender, EventArgs e)

{

this.txtProperties.Text = null;

sourceFileName = null;

openFileDialog.ShowDialog();

if (!System.IO.File.Exists(sourceFileName))

{

MessageBox.Show("The selected file either does not exist or you didn't pick any.");

return;

}

this.ClientSize = new System.Drawing.Size(415, 158);

this.txtProperties.Show();

this.btnHide.Show();

StringBuilder stbOutput = new StringBuilder("");

System.IO.FileAttributes Attributes = System.IO.File.GetAttributes(sourceFileName);

stbOutput.Append("Date of Creation: " + System.IO.File.GetCreationTime(sourceFileName) + "rn");

stbOutput.Append("Date of Modification: " + System.IO.File.GetLastWriteTime(sourceFileName) + "rn");

stbOutput.Append("Date of Last Access: " + System.IO.File.GetLastAccessTime(sourceFileName) + "rn");

stbOutput.Append("Attributes: rn");

stbOutput.Append("Archive: " + Convert.ToBoolean((Attributes & System.IO.FileAttributes.Archive) == (System.IO.FileAttributes.Archive)) + " ");

stbOutput.Append("Directory: " + Convert.ToBoolean((Attributes & System.IO.FileAttributes.Directory) == (System.IO.FileAttributes.Directory)) + "rn");

stbOutput.Append("Encrypted: " + Convert.ToBoolean((Attributes & System.IO.FileAttributes.Encrypted) == (System.IO.FileAttributes.Encrypted)) + " ");

stbOutput.Append("Hidden: " + Convert.ToBoolean((Attributes & System.IO.FileAttributes.Hidden) == (System.IO.FileAttributes.Hidden)) + "rn");

stbOutput.Append("Normal: " + Convert.ToBoolean((Attributes & System.IO.FileAttributes.Normal) == (System.IO.FileAttributes.Normal)) + " ");

stbOutput.Append("Read-only: " + Convert.ToBoolean((Attributes & System.IO.FileAttributes.ReadOnly) == (System.IO.FileAttributes.ReadOnly)) +"rn");

stbOutput.Append("System: " + Convert.ToBoolean((Attributes & System.IO.FileAttributes.System) == (System.IO.FileAttributes.System)) + " ");

stbOutput.Append("Temporary: " + Convert.ToBoolean((Attributes & System.IO.FileAttributes.Temporary) == (System.IO.FileAttributes.Temporary)));

txtProperties.Text = stbOutput.ToString();

}


The above code snippet is more long than complex. It surely isn't as hard as it seems. After the source file is chosen, we build a string called stbOutput. We build this with the data that's going to be displayed. Working this way is easy because we just use the Append method. We will use the System.IO.File.GetAttributes() to "grab" the attributes of the source file in a structure with System.IO.FileAttributes type.

Now that we have our structure, we just need to examine its content. We go through the structure using the System.IO.FileAttributes.<attribute goes here> as a basis for our comparison and if they match, then we simply append a "TRUE" in our string or "FALSE" if the particular attribute isn't set for the source file. Once we've analyzed enough attributes, then we actually display our string on the txtProperties text box.

Finally, as I mentioned earlier, we need the btnHide button to conceal the unnecessary components if the user opts to go back to the main menu. S/he might have clicked on Properties, but then decided that Renaming the file would be a better option. Clicking on btnHide resets txtProperties, conceals both itself (btnHide) and the txtProperties, and ultimately resizes frmMain to its original size.


private void btnHide_Click(object sender, EventArgs e)

{

this.txtProperties.Text = "rn";

this.btnHide.Hide();

this.txtProperties.Hide();

this.ClientSize = new System.Drawing.Size(145, 158);

}


And with this we can finally finish our project. If you could follow along and have done everything as it was stated, then your application should run without problems. Regardless, if yours doesn't work, on the next page you can download the archived project and see what you did wrong. You can play around with it.

Final Words

We've come to the end of this tutorial. I truly hope that this article will be helpful throughout your C# endeavors. One thing is for sure, managing files is necessary everywhere and you will use the things we learned here many times. Below you will find the link to the csharp.zip archive. Grab it, extract it, and enjoy.



Let me finish this tutorial by attaching a screen shot of the final product. The following screen shot is how our little tool looks if the user opts for Properties and wants to see the file attributes of a particular file. I've chosen "notepad.exe."


Please do understand that this tutorial article mainly targets the beginner or intermediate programmer -- generally C# coders that are familiar with the syntax of the language, but haven't had the chance to work with the files yet. Therefore, I started almost from the beginning, but went ahead assuming that the reader was able to follow along. It doesn't target the pros.

If you still have unanswered questions or are facing some programming issues, then don't hesitate to join our community at "DevHardware Forums" or any other forum in the Shed network that specializes in coding, such as the "DevShed Forums." Our communities are friendly and we're doing our best to help. See you there.

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 4 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials