Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to create a directory
It must first check to see if directory exist. If not create one.

public void createNewFolder()
{
  DirectoryInfo di = new DirectoryInfo("..\\DATA\\" + BUSINESSNAME.Text);

  //Check to see if company directory exist
  if (!di.Exists)
  {
    try
    {
     di = Directory.CreateDirectory(this.Server.MapPath("..\\DATA\\" + BUSINESSNAME.Text));
    }
    catch
    {
     this.Page.Response.Write("Director was not created.");
    }
  }
   else
   {
    this.Page.Response.Write("Director exist already. Please go to edit/update Page.");
   }
}
Posted

Why not debug it and see if it works correctly? At it's current state it'll just check one relative directory which should be under predefined DATA directory.

Another note. In my opinion it would be more elegant (and likely to be re-usable) to pass the directory name as a parameter than to hard code it into the method.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 8-Apr-11 15:29pm    
Absolutely, my 5. More to it, not following your second advice would not be acceptable.
--SA
Wendelius 8-Apr-11 15:37pm    
Thanks :)
I would suggest that it needs some revision.

At present, you are checking one folder, then (potentially) creating one with a different path. Instead, try building a new string, and using that exclusivly:
string path = Server.MapPath(@"..\DATA\" + BUSINESSNAME.Text);


Secondly, why not use the same DirectoryInfo as you checked with anyway?
DirectoryInfo di = new DirectoryInfo(path);
if (!di.Exists)
    {
    try
        {
        di.Create();
        }
    catch (Exception ex)
        {
        ...
        }
    }
else
    {
    ...
    }
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 8-Apr-11 15:30pm    
Or yes, it does need revision! My 5.
--SA
When you check to see if your directory exists, you are not checking the same path as the path you are using to create the new directory.

You check to see if "..\\DATA\\" + BUSINESSNAME.Text exists, but then you create this.Server.MapPath("..\\DATA\\" + BUSINESSNAME.Text).

The DirectoryInfo object should probably use the same this.Server.MapPath("..\\DATA\\" + BUSINESSNAME.Text) path.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 8-Apr-11 15:31pm    
What would you expect if OP does hard-coding? That is a real problem... Mika is right.
--SA
Kythen 8-Apr-11 15:35pm    
You are absolutely correct. I was just trying to point out the plain path vs. Server.MapPath discrepancy which hadn't been pointed out yet at the time I wrote this answer. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900