none
Path.Combine(string1, string2, string3) does not work as expected. Why? RRS feed

  • Question

  • I have this code:

    String strErrorFile = Path.Combine(
      MYAPP.Properties.Settings.Default.PreviousReportPath,
      Path.GetFileNameWithoutExtension(strFile),
      "_ERRORS.CSV");
    

    But the result is excluding the file name (second parameter). The only way I get it to work is if I do this:

    String strErrorFileName = String.Format("{0}_ERRORS.CSV", Path.GetFileNameWithoutExtension(strFile));
    
    String strErrorFile = Path.Combine(
     MYAPP.Properties.Settings.Default.PreviousReportPath,
     strErrorFileName);
    

    This works correctly. Why does the first approach fail? strFile is valid because it has been used to load a file up and it came from the OpenFileDialog.FileNames enumerator.

    Friday, February 20, 2015 11:35 AM

Answers

  • I tried your first code and it did work, though I wonder if its doing what you require it  to do, as the result will not be the same as your second example.

    The Path.Combine() method pieces together all parts as though they were bits of a path. So if my first argument is "c:\temp", and my second argument (the filename) is "somefile", then the result in strErrorFile will be:

    c:\temp\somefile\_ERRORS.CSV

    i.e. the name of your file will be taken and inserted into the path as a folder, rather than combined with the fragment of filename at the end. This is as expected.

    It looks like your second example is actually doing what you are actually trying to achieve!

    • Proposed as answer by RJP1973 Friday, February 20, 2015 11:44 AM
    • Marked as answer by Chuckie72 Friday, February 20, 2015 11:55 AM
    Friday, February 20, 2015 11:44 AM

All replies

  • I tried your first code and it did work, though I wonder if its doing what you require it  to do, as the result will not be the same as your second example.

    The Path.Combine() method pieces together all parts as though they were bits of a path. So if my first argument is "c:\temp", and my second argument (the filename) is "somefile", then the result in strErrorFile will be:

    c:\temp\somefile\_ERRORS.CSV

    i.e. the name of your file will be taken and inserted into the path as a folder, rather than combined with the fragment of filename at the end. This is as expected.

    It looks like your second example is actually doing what you are actually trying to achieve!

    • Proposed as answer by RJP1973 Friday, February 20, 2015 11:44 AM
    • Marked as answer by Chuckie72 Friday, February 20, 2015 11:55 AM
    Friday, February 20, 2015 11:44 AM
  • Thank you. I had not spotted that the filename had been inserted as part of the path itself. I appreciate your explanation and assistance.

    Friday, February 20, 2015 11:56 AM