Slash and Escape Problems in C#

I wanna write some data to Excel in C# with COM, but I got a problem saving. Let's see the code:

  1. workSheet.SaveAs("c:/users/amare/sub.xls");

    The code above will cause an error:

    "Microsoft Excel can't open the file c://users/amare/sub.xls."

    But the code below works fine:

  2. workSheet.SaveAs("c:\\users/amare/sub.xls");
  3. workSheet.SaveAs(@"c:\users\amare\sub.xls");

Now I'm quite confused about this situation. I know 2) and 3) are absolutely right, but I'm used to writing code like 1):

StreamWriter sw = new StreamWriter("c:/users/amare/desktop/file.txt");

This always works fine. So I want to know why it does not this time. Apparently C# escapes the path incorrectly in 1).


Apparently workSheet.SaveAs() does its own validation and fix-up of the path. So you are (rightfully) being punished for using an invalid format. That format is usually accepted but 'usually' is not the same as 'always'.

I have tried your path and sure, it fails with a message stating the path is not valid or is not writable. I have also tried to write the file inside the Documents subfolder (where the write permission is granted) but the same error appears again. So it is definitively a problem inside the parser of the Excel interop. I think that, in windows, you should avoid this path separator.

If you use verbatim strings defined prefixing the string with the @ char


all works as expected.

Need Your Help

How to implement Lazy Load in my situation? lazy-loading ajaxcontroltoolkit

I have a sysadmin tab and when clicked generates a lot of ajax tabpanel which is dynamic and database driven ...

Memory problems with JavaScript + CSS3 animations. How to improve?

javascript jquery memory-leaks css-animations

I have created a loop of animations. Once one animation is finished, it triggers next one and so on. Seems that when I keep my browser open for 1-2 minutes, it starts to slow down and eating more and