.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

Friday, January 06, 2006

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

0 comments: