In my DRC project, I found a bug specifically caused by incorrect file path.
My approach was the Base folder path in my app.config / Settings and then use relative paths for all the resources I need to store in a database. Seems like a solid plan. Actually, been using this approach for 10+ years now... what went wrong?
Recently, I've been using Resharper tool to tighten up my code. During my review of the code, I found where I had some manually concatenated paths using string.Format(). With an eye to porting my application to iOS or Android using Mono, I thought building paths from simple strings simply won't do. Better to use System.IO.Path.Combine() right?
Wrong! After converting this code to use Path.Combine() errors occurred. Impossible I thought, the paths are correct. I found this issue on StackOverflow:
Why Does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar
In my testing I found this:
Path path + subfolder + file name
System.IO.Path.Combine(@"C:\DRC_Data","USA","48cnty.dbf")
"C:\\DRC_Data\\USA\\48cnty.dbf" - PASS
System.IO.Path.Combine(@"C:\DRC_Data\","USA","48cnty.dbf")
"C:\\DRC_Data\\USA\\48cnty.dbf" + PASS
System.IO.Path.Combine(@"C:\DRC_Data",@"USA",@"\48cnty.dbf")
"\\48cnty.dbf" - FAIL
System.IO.Path.Combine(@"C:\DRC_Data\",@"\USA","48cnty.dbf")
"\\USA\\48cnty.dbf" - FAIL
System.IO.Path.Combine(@"C:\DRC_Data\",@"USA",@"\48cnty.dbf")
"\\48cnty.dbf" = FAIL
System.IO.Path.Combine(@"C:\DRC_Data\",@"\USA\",@"48cnty.dbf")
"\\USA\\48cnty.dbf" - FAIL
Now, I'm not going to declare Path.Combine() useless for building paths with relative elements but there needs to a an option set for Path.Combine() does not assume every element that starts with a backslash as a start of a root path.
Path.Combine() works as per spec but it's not what I would have expected either.
Bottom line, it is a helper function that should be more helpful!
No comments:
Post a Comment