Slash and escape problems in C #

I want to write some data in Excel in C # using COM, but I have a problem with saving. Check out the code:

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

    The above code will throw an error:

    "Microsoft Excel cannot open the file c: //users/amare/sub.xls."

    But the code below works fine:

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

Now I am completely confused by this situation. I know 2) and 3) is 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(); 

It always works well. So I want to know why this is not this time. Apparently, C # chose the wrong path in 1).

+4
source share
2 answers

Apparently workSheet.SaveAs() does its own validation and path correction. Thus, you (rightfully) are punished for using an invalid format. This format is generally accepted, but "usually" does not match "always."

+4
source

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

If you use verbatim strings , define the string prefix using @ char

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

everything works as expected.

+1
source

All Articles