Question

I was looking for a way to get a relative directory and file path (both) either directly or from a full path. It seems I cannot find a satisfying answer... and I googled a lot.

The problem is that I need to upload files on FTP and i need the format "Hostftp:port/"+"Directory/subdirectory" to create the ftp request

Example

myftp:8008/Users
myftp:8008/Users/Data
myftp:8008/Users/Data/Anagraphics
myftp:8008/Work

etc etc.

I pick the files from my computer so they are like

C:\users\MyPc\UsersData\Users
C:\users\MyPc\UsersData\Users\Data
C:\users\MyPc\UsersData\Users\Data\Anagraphics
C:\users\MyPc\UsersData\Work

I want them listed like

Users
Users\Data
Users\Data\Anagraphics
Work

so I can concatenate the string and make

myftp:8008/Users
myftp:8008/Users/Data
myftp:8008/Users/Data/Anagraphics
myftp:8008/Work

How to do it???

Was it helpful?

Solution

List<string> paths = new List<string>()
{
    @"C:\users\MyPc\UsersData\Users",
    @"C:\users\MyPc\UsersData\Users\Data",
    @"C:\users\MyPc\UsersData\Users\Data\Anagraphics",
    @"C:\users\MyPc\UsersData\Work"
};

var MatchingChars =
  from len in Enumerable.Range(0, paths.Min(s => s.Length)).Reverse()
  let possibleMatch = paths.First().Substring(0, len)
  where paths.All(f => f.StartsWith(possibleMatch))
  select possibleMatch;

var LongestDir = Path.GetDirectoryName(MatchingChars.First());
var ftpPaths = paths.Select(p=>Path.Combine("myftp:8008",p.Substring(LongestDir.Length +1)).Replace(@"\", "/"));

ftpPaths :

myftp:8008/Users 
myftp:8008/Users/Data 
myftp:8008/Users/Data/Anagraphics 
myftp:8008/Work 

To Find the common file path from list of paths I used one of answer of this SO Question

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top