2012-10-02 22 views
10

¿Cuál es la forma más fácil de obtener la letra de unidad en una ruta de archivo tipo de URI comoDrive de ruta del archivo tipo de URI en C#

file:///D:/Directory/File.txt 

Yo sé que puedo hacer (ruta que aquí hay una cadena que contiene el texto arriba)

path = path.Replace(@"file:///", String.Empty); 
path = System.IO.Path.GetPathRoot(path); 

pero se siente un poco torpe. ¿Hay alguna manera de hacerlo sin usar String.Replace o similar?

+0

expresión regular '\/(\ w): \ /'? – Prasanth

Respuesta

15
var uri = new Uri("file:///D:/Directory/File.txt"); 
if (uri.IsFile) 
{ 
    DriveInfo di = new DriveInfo(uri.LocalPath); 
    var driveName = di.Name; // Result: D:\\ 
} 
+0

+1 para un enfoque mucho mejor – Habib

+0

Sería mejor si agrega un cheque 'if (uri.IsFile)' – Habib

+0

Gracias por la sugerencia. –

2

Esto se puede hacer usando el siguiente código:

string path = "file:///D:/Directory/File.txt"; 
    if(Uri.IsWellFormedUriString(path, UriKind.RelativeOrAbsolute)) { 
     Uri uri = new Uri(path); 
     string actualPath = uri.AbsolutePath; 
    } 
Cuestiones relacionadas