4
\$\begingroup\$

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");
\$\endgroup\$
1
  • 4
    \$\begingroup\$ What exactly do you hate about this code? Are you looking for a 1-line version of it? \$\endgroup\$ May 23, 2011 at 21:43

2 Answers 2

8
\$\begingroup\$

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");
\$\endgroup\$
6
\$\begingroup\$

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

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

same kind of thing for building your file name.

\$\endgroup\$
5
  • \$\begingroup\$ I'm not using 4.0 \$\endgroup\$
    – MVCylon
    May 24, 2011 at 12:53
  • 6
    \$\begingroup\$ Thats ok, they were nice enough to build it into .NET since 1.1 I think \$\endgroup\$ May 24, 2011 at 21:33
  • \$\begingroup\$ It's burried in under System.IO :) \$\endgroup\$ May 24, 2011 at 21:49
  • \$\begingroup\$ 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 \$\endgroup\$
    – MVCylon
    May 25, 2011 at 12:11
  • \$\begingroup\$ @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 \$\endgroup\$
    – peter
    Jul 11, 2016 at 20:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.