2011-10-27 13 views

risposta

8

funziona sia in avanti e indietro tagliare

static string GetRootFolder(string path) 
{ 
    while (true) 
    { 
     string temp = Path.GetDirectoryName(path); 
     if (String.IsNullOrEmpty(temp)) 
      break; 
     path = temp; 
    } 
    return path; 
} 
+0

Ooh, è molto più succinta. – bobbymcr

+2

Non pensare che restituirà la prima directory come richiesto. Ma dal momento che è stato contrassegnato come la risposta sembra servire allo scopo ... nel qual caso la domanda è errata. Si prega di aggiornare – aateeque

+0

Finché la prima directory non inizia con nessun tipo di barra, altrimenti restituirà la barra. Per il mio caso d'uso negli URL web, ho semplicemente rifilato il taglio iniziale. –

6

Sembra che si potrebbe utilizzare il metodo string.Split() sulla corda, poi prendete il primo elemento.
esempio (non testata):

string str = "foo\bar\abc.txt"; 
string str2 = "bar/foo/foobar"; 


string[] items = str.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries); 

Console.WriteLine(items[0]); // prints "foo" 

items = str2.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries); 
Console.WriteLine(items[0]); // prints "bar" 
5

La soluzione più robusta sarebbe usare DirectoryInfo e FileInfo. Su un sistema basato su Windows NT dovrebbe accettare forward o backslash per i separatori.

using System; 
using System.IO; 

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     Console.WriteLine(GetTopRelativeFolderName(@"foo\bar\abc.txt")); // prints 'foo' 
     Console.WriteLine(GetTopRelativeFolderName("bar/foo/foobar")); // prints 'bar' 
     Console.WriteLine(GetTopRelativeFolderName("C:/full/rooted/path")); // ** throws 
    } 

    private static string GetTopRelativeFolderName(string relativePath) 
    { 
     if (Path.IsPathRooted(relativePath)) 
     { 
      throw new ArgumentException("Path is not relative.", "relativePath"); 
     } 

     FileInfo fileInfo = new FileInfo(relativePath); 
     DirectoryInfo workingDirectoryInfo = new DirectoryInfo("."); 
     string topRelativeFolderName = string.Empty; 
     DirectoryInfo current = fileInfo.Directory; 
     bool found = false; 
     while (!found) 
     { 
      if (current.FullName == workingDirectoryInfo.FullName) 
      { 
       found = true; 
      } 
      else 
      { 
       topRelativeFolderName = current.Name; 
       current = current.Parent; 
      } 
     } 

     return topRelativeFolderName; 
    } 
} 
0

Ecco un altro esempio nel caso in cui il vostro percorso se seguente formato:

string path = "c:\foo\bar\abc.txt"; // or c:/foo/bar/abc.txt 
string root = Path.GetPathRoot(path); // root == c:\ 
+0

C'è _qualsiasi_ Sistema operativo che utilizza la convenzione 'c:/foo/bar/abc.txt'? –

+0

È necessario eseguire il escape delle barre rovesciate o utilizzare stringhe letterali ('@" ... "'). – bobbymcr

+0

L'escape è necessario, sono d'accordo, altrimenti la stringa non è valida. Indipendentemente dalle convenzioni, l'esempio prende di mira la domanda dell'utente e se "c: /foo/bar/abc.txt" è fornito, il codice funziona ancora. – Dan

1

Sulla base della domanda si chiede, il seguente dovrebbe lavoro:

public string GetTopLevelDir(string filePath) 
    { 
     string temp = Path.GetDirectoryName(filePath); 
     if(temp.Contains("\\")) 
     { 
      temp = temp.Substring(0, temp.IndexOf("\\")); 
     } 
     else if (temp.Contains("//")) 
     { 
      temp = temp.Substring(0, temp.IndexOf("\\")); 
     } 
     return temp; 
    } 

Quando viene passato foo\bar\abc.txt sarà foo come volevamo- stesso per il/caso

1

Sulla base della risposta fornita da Hasan Khan ...

private static string GetRootFolder(string path) 
{ 
    var root = Path.GetPathRoot(path); 
    while (true) 
    { 
     var temp = Path.GetDirectoryName(path); 
     if (temp != null && temp.Equals(root)) 
      break; 
     path = temp; 
    } 
    return path; 
} 

Questo darà la cartella di livello superiore

+0

Ecco la tua risposta. Usa questo metodo per girare: foo \ bar \ abc.txt -----> pippo bar/foo/foobar -----> bar – Tyrant

Problemi correlati