Esiste un metodo .NET Framework per convertire gli URI dei file in percorsi con lettere di unità?

StackOverflow https://stackoverflow.com/questions/278761

  •  07-07-2019
  •  | 
  •  

Domanda

Stavo cercando qualcosa come Server.MapPath nel regno ASP.NET per convertire l'output di Assembly.GetExecutingAssembly (). CodeBase in un percorso di file con lettera di unità.

Il seguente codice funziona per i casi di test che ho provato:

private static string ConvertUriToPath(string fileName)
{
    fileName = fileName.Replace("file:///", "");
    fileName = fileName.Replace("/", "\\");
    return fileName;
}

Sembra che ci dovrebbe essere qualcosa in .NET Framework che sarebbe molto meglio - semplicemente non sono stato in grado di trovarlo.

È stato utile?

Soluzione

Prova a guardare Uri.LocalPath proprietà.

private static string ConvertUriToPath(string fileName)
{
   Uri uri = new Uri(fileName);
   return uri.LocalPath;

   // Some people have indicated that uri.LocalPath doesn't 
   // always return the corret path. If that's the case, use
   // the following line:
   // return uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);
}

Altri suggerimenti

Ho cercato molto una risposta e la risposta più popolare sta usando Uri.LocalPath . Ma System.Uri non riesce a fornire LocalPath corretto se il percorso contiene "#". I dettagli sono qui .

La mia soluzione è:

private static string ConvertUriToPath(string fileName)
{
   Uri uri = new Uri(fileName);
   return uri.LocalPath + Uri.UnescapeDataString(uri.Fragment).Replace('/', '\\');
}

Puoi semplicemente usare Assembly.Location ?

La posizione può essere diversa da CodeBase. Per esempio. per i file in ASP.NET è probabile che venga risolto in c: \ WINDOWS \ Microsoft.NET \ Framework \ v2.0.50727 \ ASP.NET temporaneo. Vedi " Assembly.CodeBase vs. Assembly.Location " http://blogs.msdn.com/suzcook/archive/ 2003/06/26 / 57198.aspx

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top