Monday, August 16, 2010

Directory creation in c# in the selected drives available in your system

Creating a directory in c# in the selected drives available in your system.
----------------------------------------------------------------------------
The below code is used to list all the drives available in your system and allow you to create a directory in the drive you choose.


ASSSUMPTIONS MADE: THE VALIDATION ARE TO BE TAKEN CARE BY YOU.

code:
--------
ASPX:
--------



.cs code
------------

PageLoad event code:


protected void Page_Load(object sender, EventArgs e)
{

//now we need to get the list of the directories of the system
DriveInfo[] diDrive = null;
try
{
if (!IsPostBack)
{
//tdrive = new string[System.IO.DriveInfo.GetDrives().Length];
diDrive = System.IO.DriveInfo.GetDrives();

//arrDrives = System.IO.DriveInfo.GetDrives().ToArray();
ddlDrivesList.Items.Clear();


//here we are adding the drive letters to the dropdown list
foreach (DriveInfo iDrives in diDrive)
{
ddlDrivesList.Items.Add(iDrives.ToString());
}
}
}
catch (Exception)
{

throw;
}
finally
{
if (diDrive != null) diDrive = null;

}


}




Button Click code:



protected void btnCreateDirectory_Click(object sender, EventArgs e)
{
//Declaring the variables here.

try
{
lblerror.Text = string.Empty;
//verifying whether the direactory exists or not
if (System.IO.Directory.Exists(Path.Combine(ddlDrivesList.SelectedItem.ToString(), txtDirectoryName.Text)) == true)
{
lblerror.Text = "Already Exists";
}
else
{
//creating the directory
System.IO.Directory.CreateDirectory(Path.Combine(ddlDrivesList.SelectedItem.ToString(), txtDirectoryName.Text));
lblerror.Text = "directory created";
}
}
catch (Exception EX)
{
throw EX ;
}
}

No comments:

Post a Comment