Streamline code for checking if a directory exists and saving a file

I hate this code. What is the slickest way to write the following:

MyFile = f;
SaveFolder = Server.MapPath("\\") + "returns\\";
if(!System.IO.Directory.Exists(SaveFolder) )
{
System.IO.Directory.CreateDirectory(SaveFolder);
}
MyFile.SaveAs(SaveFolder + "2011" + "000-00-0000" + ".xlsx");

• What exactly do you hate about this code? Are you looking for a 1-line version of it? – carlosfigueira May 23 '11 at 21:43

Since CreateDirectory does nothing if a directory already exists, you can do this:

MyFile = f;
SaveFolder = Path.Combine(Server.MapPath("\\"), "returns");
System.IO.Directory.CreateDirectory(SaveFolder);
MyFile.SaveAs(SaveFolder, "2011000-00-0000.xlsx");


well, for starters, use Path.Combine... eg :-

SaveFolder = Path.Combine(Server.MapPath(@"\"),"returns");


same kind of thing for building your file name.

• I'm not using 4.0 – MVCylon May 24 '11 at 12:53
• Thats ok, they were nice enough to build it into .NET since 1.1 I think – Keith Nicholas May 24 '11 at 21:33
• It's burried in under System.IO :) – Stuart Blackler May 24 '11 at 21:49
• You may be right. However, check out Microsoft's own documentation..msdn.microsoft.com/en-us/library/system.io.path.combine.aspx It only lists .Net 4.0 & Silverlight I googled this BEFORE, I posted that I wasn't using 4.0 – MVCylon May 25 '11 at 12:11
• @MVCylon msdn isn't maybe that clear about it, but the trick is, only one Combine override was available pre .Net 4 - msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.80).aspx that's why you could choose it – peter Jul 11 '16 at 20:57