Working with Files in C#


This article was contributed by Anand Narayanaswamy.

In this article, you will learn how to manipulate directories and files in your system. Further, we will discuss how to read from and write to a file by using the powerful .NET classes.

The Namespace

System.IO provides all the necessary classes, methods, and properties for manipulating directories and files. Table 1 elaborates the main classes under this namespace.

Class Purpose/Use
Binary Reader and Writer Read and write primitive data types
Directory, File, DirectoryInfo, and FileInfo Create, delete, and move files and directories. Get specific information about the files by making use of the properties defined in these classes.
FileStream Access the files in a random fashion
MemoryStream Access data stored in memory
StreamWriter and StreamReader Read and write textual information
StringReader and StringWriter Read and write textual Information from a string buffer

Table 1—Classes under System.IO

Working with DirectoryInfo and FileInfo classes

The base class of DirectoryInfo and FileInfo is FileSystemInfo. This is an abstract class, meaning you can't instantiate this class. But you can use the properties defined by this class. Table 2 elaborates its properties and methods.

Properties Purpose/Use
Attributes Returns attributes associated with a file. Takes FileAttributes enumeration values
CreationTime Returns the time of creation of the file
Exists Checks whether a supplied file is a directory or not
Extension Returns the file extension
LastAccessTime Returns last accessed time of the file
FullName Returns the full path of the file
LastWriteTime Returns the time of last written activity to the file
Name Returns the name of a given file
Delete() Deletes a file. Be careful when using this method.

Table 2—Members of FileSystemInfo class

The DirectoryInfo class provides methods for creating, moving, and deleting directories. To make use of the above properties, create an object of the DirectoryInfo class as shown in Listing 1:

Listing 1

DirectoryInfo dir1 = new DirectoryInfo(@"F:\WINNT");

You then can access the properties by using the object dir1, as shown in the code fragment in Listing 2:

Listing 2

Console.WriteLine("Full Name is : {0}", dir1.FullName);
Console.WriteLine("Attributes are : {0}",
                   dir1.Attributes.ToString());

You can also apply the values of FileAttributes enumeration. Its values are shown in Table 3.

Properties Purpose/Use
Archive Returns the file's Archive status
Compressed Returns whether the file is compressed or not
Directory Returns whether the file is a directory or not
Encrypted Returns whether the file is encrypted or not
Hidden Returns whether the file is hidden or not
Offline Signifies that the data is not available
ReadOnly Indicates that the file is read only
System Indicates that the file is a System file (probably a file under the Windows folder)

Table 3—FileAttributes Enumeration Values

Working with Files under a Directory

Suppose that you want to list all BMP files under the f:\Pictures directory. You can write a code as shown in the code snippet given in Listing 3:

Listing 3

DirectoryInfo dir = new DirectoryInfo(@"F:\WINNT");
FileInfo[] bmpfiles = dir.GetFiles("*.bmp);
Console.WriteLine("Total number of bmp files", bmpfiles.Length);
Foreach( FileInfo f in bmpfiles)
{
  Console.WriteLine("Name is : {0}", f.Name);
  Console.WriteLine("Length of the file is : {0}", f.Length);
  Console.WriteLine("Creation time is : {0}", f.CreationTime);
  Console.WriteLine("Attributes of the file are : {0}",
                     f.Attributes.ToString());
}

Creating Subdirectories

You can easily create a subdirectory. Listing fragment 4 describes how to create a subdirectory called MySub under the Sub directory.

Listing 4

DirectoryInfo dir = new DirectoryInfo(@"F:\WINNT");
try
{
  dir.CreateSubdirectory("Sub");
  dir.CreateSubdirectory(@"Sub\MySub");
}
catch(IOException e) 
{
  Console.WriteLine(e.Message);
}

Creating Files by Using the FileInfo Class

With the FileInfo class, you can create new files, access information about the files, delete, and move files. This class also provides methods for opening, reading from, and writing to a file. Listing 5 shows how to create a text file and access its information like its creation time, full name, and so forth.

Listing 5

FileInfo fi = new FileInfo(@"F:\Myprogram.txt");
FileStream fstr = fi.Create();
Console.WriteLine("Creation Time: {0}",f.CreationTime);
Console.WriteLine("Full Name: {0}",f.FullName);
Console.WriteLine("FileAttributes: {0}",f.Attributes.ToString());

//Way to delete Myprogram.txt file.

Console.WriteLine("Press any key to delete the file");
Console.Read();
fstr.Close();
fi.Delete();

Understanding the Open() Method

The FileInfo class defines a method named Open() with which you can create files by applying the values of the FileMode and FileAccess enumerations. The code snippet in Listing 6 describes its usage:

Listing 6

FileInfo f = new FileInfo("c:\myfile.txt");
FileStream s = f.Open(FileMode.OpenorWrite, FileAccess.Read);

You then can read from and write to a file by using the object 's'. In the overloaded Open() method, permission is given only for reading from a file. If you want to write to a file, you have to apply the ReadWrite value of FileAccess enumeration. Tables 4 and 5 describe the values of the FileMode and FileAccess enumerations.

Values Purpose/Use
Append Opens the file and adds data. This should be used with the FileAccess Write Enumeration value.
Create Creates a new file. Overwrites any existing file.
CreateNew Creates a new file. If the file already exists, IOException is thrown.
Open Opens an existing file
OpenOrCreate Opens a new file. If there is no file, it creates a new file.
Truncate Truncates an existing file

Table 4—FileMode Enumeration values

Values Purpose/Use
Read Data can be read (retrieved) from the file
ReadWrite Data can be added to and retrieved from the file
Write Data can be added to the file

Table 5—FileAccess Enumeration values

Writing to a Text File by Using the StreamWriter Class

You can easily write texts or other information to a file by using the CreateText() method of the FileInfo class. However, you have to obtain a valid StreamWriter. It's this StreamWriter reference that provides the required functionalities for writing to a file. To illustrate, Listing 7 writes a series of texts to the Mytext.txt file.

Listing 7

FileInfo f = new FileInfo("Mytext.txt")
StreamWriter w = f.CreateText();
w.WriteLine("This is from");
w.WriteLine("Chapter 6");
w.WriteLine("Of C# Module");
w.Write(w.NewLine);
w.WriteLine("Thanks for your time");
w.Close();

Reading from a Text File

You can read from a Text file by using the StreamReader class. For this, you have to specify the file name using the static OpenText() method of the File class. Listing 8 reads the contents that we have written in Listing 7:

Listing 8

Console.WriteLine("Reading the contents from the file");
StreamReader s = File.OpenText("Mytext.txt");
string read = null;
while ((read = s.ReadLine()) != null)
{
  Console.WriteLine(read);
}
s.Close();

About the Author

Anand Narayanaswamy works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, Software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials.



About the Author

Anand Narayanaswamy

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com)which provides affordable web hosting services. He is the author of Community Server Quickly (http://www.packtpub.com/community-server/book). Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in

Comments

  • Ghd rettetang billig er likt av venninne i sommeren 2013

    Posted by carpinteyroequ on 06/14/2013 09:48am

    [url=http://www.rettetangnorgenews.net/]rettetang ghd[/url] Ghd er i ferd med å lansere ghd luften, en salong styrke hårtørker som kommer til å lage bølger i håret bransjen. Å promotere den nye ghd luften, Katy Perry hadde en glamorøs photoshoot hvor hun ble stylet som en havfrue. Rosa hår og en glitrende hale – er det noen ser som ikke passer Katy? Vi må bare vente og se! [url=http://www.rettetangnorgenews.net/]CHI rettetang[/url] Når vi vet ghd rettetang norge kan opprette et utvalg av stilfull hår. Så vi ønsker alle å ha et slikt verktøy. For å lar oss easilycreate krøller og bølger, så vel som den perfekte rett hår. Men vet du hvilke ghd rettetang er det beste valget for deg. Vi bør velge ghd rettetang som passer for deg, heller enn å følge noen andres måte å kjøpe den. [url=http://www.rettetangnorgenews.net/]ghd rettetang norge[/url] og er perfekt for curling, retting eller bølger. Selvfølgelig har det alle de fantastiske funksjonene i GHD Gold Classic, som en automatisk-søvn funksjonen, universell spenning for bruk på reiser, og en ekstra lang strømkabel for enkel use.Add litt glamour til styling rutine med ghd metallic samlingen.

    Reply
  • Nye Beats By Dr. Dre Classic skabe et nyt liv

    Posted by wanzixiao on 06/03/2013 11:50pm

    [url=http://www.beatsbydrdredanmark.webgarden.com/]beats by dre danmark[/url] i hvert fald set er en god musik altid være påkrævet, og hovedtelefonerne som Dre beats forbedrer sådan musik, så du har lyst til himlen. I denne artikel vil vi diskutere, hvor langt disse bemærkelsesværdige hovedtelefoner (Dre beats hovedtelefoner) er i stand til, og hvordan strålende det kan støtte dig til at få essensen af musikken. For din korte viden – Monster har formået at kombinere stil med funktionalitet i Dr. Dre udvalg af hovedtelefoner understøtter disse ikke blot at se godt, men også at gøre lydkvaliteten endnu bedre. Hvis du kigger ind i dens specifikationer så du kan indse det, at de beats fra Dre hovedtelefoner lyd er altid velafbalanceret med en varm mellemtone og dunkende bas. [url=http://www.beatsbydrdredanmark.webstarts.com/]Køb høretelefoner billig[/url] I hvad der kunne opfattes som en anelse ironisk, har p-piller en udsende at kanter mod fladere side af tingene, i stedet for at pumpe ud ublu mængder af bas. Det er ikke til at sige, at det ikke kan gengive bas ved alle, det er bare ikke i fokus her. Dette fladere output ser ud til at være en stor del af hvad der holder det fra fordrejende, men vi bør være klart, at lyden her er mange gange endnu bedre på p-piller. Behageligt, er højttalerne også vinklet lidt opad, hvilket gør for en mærkbart mere naturlig lytteoplevelse. Vores eneste anden bekymring for tiden er, at Bluetooth-forbindelse med vores iPhone 5 havde sprutte lejlighedsvis som en vinylplade, men det er for tidligt at sige, om problemet vil være i overensstemmelse i løbet af fremtidig brug. Vi er stadig en måder væk fra at være i stand til endeligt at give dig en thumbs up på p-piller, men – i hvert fald i første omgang, det ser ud som det let blæser den Jambox og lignende højttalere ud af vandet. [url=http://www.beatsbydrdredanmark.webstarts.com/]beats by dre danmark[/url] at undlade lyd i høretelefonerne for en stund, hvis der skulle dukke noget uventet op i din tilværelse.Kassen indeholder naturligvis Beats by Dr. Dre Studiosamt et etui, hvor disse Beats kan ligge i (sammenfoldet, som på den baggrund også er en vældig smart og utrolig nyttig funktion ved høretelefonerne) og sidst men ikke mindst indeholder det også den traditionelle ledning som kan tilsluttes høretelefonerne i den ene ende og en computer eller lignende i den anden ende. Ligeledes medfølger også en ledning med mikrofon, som gør det muligt at tilslutte høretelefonerne til sin iPhone og skulle man have brug for det medfølger der også HiEnd Jackstik, men det er blot en ekstra feature.

    Reply
  • A file should not be moved to another folder, if the is in open condition

    Posted by Divya on 04/18/2013 03:04am

    Kindly give me code for the above query...

    Reply
  • bootless nfl jerseys from china

    Posted by hlgernoneyzy on 03/12/2013 12:38pm

    cheap Clarisonic cleansers clarisonic online shop Clarisonic cleansers outlet discount clarisonic mia 2 clarisonic mia canada cheap clarisonic canada cheap clarisonic uk clarisonic uk authentic mlb jersey new nba jerseys

    Reply
  • Superb

    Posted by Chanpreet on 04/24/2012 03:25am

    sir its superb explained by taking easy examples.

    Reply
  • Generic File names

    Posted by BradB on 01/18/2010 12:34pm

    Can I check to see if a file that begins with 'x' exists as opposed to a specific file name?

    Reply
  • Thank you.

    Posted by cipher_nemo on 09/25/2007 11:24am

    Perfect! This is exactly what I was looking for to get an array of files in a directory. I used this as a reference for creating my own file info class to get files in a directory according to a file filter. Thank you for spending the time to write it, even if this article is from 2002. It really helps those Googling it for years to come. :-)

    Reply
  • CreationTime better for SET than GET

    Posted by rox.scott on 03/25/2005 12:09pm

    I've found the CreationTime property useless for finding the actual creation time of files, unless I set it myself. This is because of Windows 'File Tunneling' behaviour. http://www.devcity.net/Articles/133/1/article.aspx

    Reply
  • Good Article

    Posted by forsrinivasan on 12/27/2004 01:45am

    This Article really good and easy for the Developers who are new to C#.

    Reply
  • code has errors. It should be:

    Posted by Legacy on 04/16/2003 12:00am

    Originally posted by: Bob Bevers

    There is a missing quote on line 2.
    
    The "F" in foreach should not be capitalized.
    The code should be:

    DirectoryInfo dir = new DirectoryInfo(@"C:\AppNet\C# Projects\test\files");
    FileInfo[] bmpfiles = dir.GetFiles("*.bmp");
    Console.WriteLine("Total number of bmp files", bmpfiles.Length);
    foreach(FileInfo f in bmpfiles)
    {
    Console.WriteLine("Name is : {0}", f.Name);
    Console.WriteLine("Length of the file is : {0}", f.Length);
    Console.WriteLine("Creation time is : {0}", f.CreationTime);
    Console.WriteLine("Attributes of the file are : {0}",
    f.Attributes.ToString());
    }

    • Typos could happen

      Posted by JonnyPoet on 03/05/2008 04:54pm

      Hopefully people reading articles like this are able to do a simple debug and correct Typos if some happens in an article. BTW great article. thx a lot for contributing it. And thx to Bob too to correct the Typos, as this helps unexpierienced programmers too.

      Reply
    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds