how to check if a directory exists / and create it if it doesn't

  • Thread starter Thread starter CCLeasing
  • Start date Start date
C

CCLeasing

If (Directory.Exists(@"c:\indigo\" + txtOfficial + @"\" +
comOffice.Text + @"\" + numTerm.Value.ToString()))
{
storereport();
}
else

{
Directory.CreateDirectory(@"c:\indigo\" + txtOfficial +
@"\" + comOffice.Text + @"\" + numTerm.Value.ToString());
}

this isn't compiling, and else is being underlined as wrong. Any
suggestions on how to fix this please?
 
if you change If to if it compiles fine for me. Keywords in c# are all lower
case

Ciaran O'Donnell
 
It's probably worth mentioning that everything is case sensitive in C#.
Second, as you have two idential strings it's worth putting them in a
variable otherwise you may forget to change one.

string dirpath = @"c:\indigo\" + txtOfficial + @"\" + comOffice.Text +
@"\" + numTerm.Value.ToString();
if (Directory.Exists(dirpath))
{
storereport();
}
else
{
Directory.CreateDirectory(dirpath);
}


Finally, there's a logic error in your code. If the directory exists it
saves the report, if it doesn't it just creates the directory and
doesn't store it. Is this more what you want?


if (!Directory.Exists(@"c:\indigo\" + txtOfficial + @"\" +
comOffice.Text + @"\" + numTerm.Value.ToString()))
{
Directory.CreateDirectory(dirpath);
}
storereport();

Finally StoreReport (methods should have capital first letters for each
word) probably also builds that path string, so perhaps make it a
member variable of the class?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top