Search code examples
c#excelescapingslash

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");
sw.WriteLine("foo-bar");
sw.close();

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


Solution

  • 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'.