More File and Directory Stuff !


Level: Beginner

In general, when you want to do anything related to Files and Directories, the namespace
of interest is System.IO. And most of the file and directory operations can be done using
one or combination of DirectoryInfo, Directory, FileInfo, or File class. Here is some common
tasks and one of many ways to do those…

1) Check if file exits :

FileInfo file = new FileInfo(“filename.txt”);
if (file.Exists)
{//file exists}

2) Check if directory exists:
Similar to the one before,
DirectoryInfo dir = new DirectoryInfo(path);
if (dir.Exists)
{ // dir exists }

3) Create a Directory
DirectoryInfo dir = new DirectoryInfo(path);
if (!dir.Exists)
{ dir.Create(); }

Using the same class, you can get the attributes, number of files present (dir.GetFiles().Length.ToString())
and more…
4) If you want to change the attribute of a File, you can do so like this…

FileInfo file = new FileInfo(“my.txt”);
// This adds just the read-only attribute.
file.Attributes = file.Attributes FileAttributes.ReadOnly;// This removes just the read-only attribute.
file.Attributes = file.Attributes & ~FileAttributes.ReadOnly;

 

5) To read or write a text file, use a StreamReader and a StreamWrite classes
To create a new file,
FileStream fs = new FileStream(“my.txt”, FileMode.Create);
6) Find files with of a certain type:
FileInfo[] files = dir.GetFiles(“*.xml”);
GetFiles() method takes an argument where you can specify the type.

Can you think of more uses, samples…post on comments…Thanx 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s