how to extract common file path from list of file paths in c#

后端 未结 9 1453
粉色の甜心
粉色の甜心 2021-01-17 15:42

What is the best way extract the common file path from the list of file path strings in c#?

Eg: I have a list 5 file paths in List variable, like below

c:\

9条回答
  •  走了就别回头了
    2021-01-17 16:14

    Use the first path as the iterator seed:

    using System;
    using System.Collections.Generic;
    using System.IO;
    
    namespace stackoverflow1
    {
        class MainClass
        {
            public static void Main (string[] args)
            {
                List paths=new List();
                paths.Add(@"c:\abc\pqr\tmp\sample\b.txt");
                paths.Add(@"c:\abc\pqr\tmp\new2\c1.txt");
                paths.Add(@"c:\abc\pqr\tmp\b2.txt");
                paths.Add(@"c:\abc\pqr\tmp\b3.txt");
                paths.Add(@"c:\abc\pqr\tmp\tmp2\b2.txt");
    
                Console.WriteLine("Found: "+ShortestCommonPath(paths));
    
            }
    
            private static String ShortestCommonPath(IList list)
            {
                switch (list.Count)
                {
                case 0: return null;
                case 1: return list[0];
                default:
                    String s=list[0];
                    while (s.Length>0)
                    {
                        bool ok=true;
                        for (int i=1;i

提交回复
热议问题