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");
dfhwze
14.1k3 gold badges40 silver badges101 bronze badges
asked May 23, 2011 at 19:36
\$\endgroup\$
1
  • 4
    \$\begingroup\$ What exactly do you hate about this code? Are you looking for a 1-line version of it? \$\endgroup\$ Commented 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");
answered May 24, 2011 at 1:02
\$\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.

answered May 23, 2011 at 21:40
\$\endgroup\$
5
  • \$\begingroup\$ I'm not using 4.0 \$\endgroup\$ Commented 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\$ Commented May 24, 2011 at 21:33
  • \$\begingroup\$ It's burried in under System.IO :) \$\endgroup\$ Commented 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\$ Commented 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\$ Commented Jul 11, 2016 at 20:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.