There's a part in my apps that displays the file path loaded by the user through OpenFileDialog. It's taking up too much space to display the whole path, but I don't want to display only the filename as it might be ambiguous. So I would prefer to show the file path relative to the assembly/exe directory.
For example, the assembly resides at "C:\Program Files\Dummy Folder\MyProgram" and the file at "C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat" then I would like it to show ".\Data\datafile1.dat". If the file is in "C:\Program Files\Dummy Folder\datafile1.dat", then I would want "..\datafile1.dat". But if the file is at the root directory or 1 directory below root, then display the full path.
What solution would you recommend? Regex?
Basically I want to display useful file path info without taking too much screen space.
EDIT: Just to clarify a little bit more. The purpose of this solution is to help user or myself knowing which file did I loaded last and roughly from which directory was it from. I'm using a readonly textbox to display the path. Most of the time, the file path is much longer than the display space of the textbox. The path is supposed to be informative but not important enough as to take up more screen space.
Alex Brault comment was good, so is Jonathan Leffler. The Win32 function provided by DavidK only help with part of the problem, not the whole of it, but thanks anyway. As for James Newton-King solution, I'll give it a try later when I'm free.
If you have a readonly text box, could you not not make it a label and set AutoEllipsis=true?
alternatively there are posts with code for generating the autoellipsis yourself: (this does it for a grid, you would need to pass i the width for the text box instead. It isn't quite right as it hacks off a bit more than is necessary, and I haven;t got around to finding where the calculation is incorrect. it would be easy enough to modify to remove the first part of the directory rather than the last if you desire.
It's a long way around, but System.Uri class has a method named MakeRelativeUri. Maybe you could use that. It's a shame really that System.IO.Path doesn't have this.
As pointed above .NET Core 2.x has implementation of
Path.GetRelativePath
.Code below is adapted from sources and works fine with .NET 4.7.1 Framework.
I have used this in the past.
There is a Win32 (C++) function in shlwapi.dll that does exactly what you want:
PathRelativePathTo()
I'm not aware of any way to access this from .NET other than to P/Invoke it, though.