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:
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:
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).
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.