How To: Get the foldername in which the file resides

We come across situation many a times where we need the name of the folder in which the file resides. Let's say the folder is as "C:\Project1\CSProj1\somename\file1.cs"

We need to get the folder "somename"

We can do this by using the namespace System.IO. Code goes as below

VB.NET

Dim file As FileInfo = New FileInfo("C:\Project1\VBProj1\somename\file1.vb")
Response.Write(file.Directory & "<br>")  'O/P -> C:\Project1\VBProj1\somename
Response.Write(file.Directory.Name)      'O/P -> somename

C#

FileInfo file = new FileInfo(@"C:\Project1\CSProj1\somename\file1.cs");
Response.Write(file.Directory + "<br>");  //O/P -> C:\Project1\CSProj1\somename
Response.Write(file.Directory.Name);     //O/P -> somename

More about FileInfo members

19 Comments

Comments have been disabled for this content.