2014-04-22 3 views
10

Voglio sapere che per assicurarsi che il file che sarà scaricato dal mio script avrà l'estensione che voglio.C'è un modo per ottenere l'estensione del file da un URL

Il file non sarà a URL del tipo:

http://example.com/this_url_will_download_a_file 

O forse sì, ma, penso che userò solo quel tipo di URL:

http://example.com/file.jpg 

io non controllerò con: Url.Substring(Url.LastIndexOf(".") - 3, 3) perché questo è un modo molto povero.

Quindi, cosa mi consigliate di fare?

+0

Si potrebbe cercare di ottenere ultima posizione di?. Se trovato, trova l'ultima posizione di. prima di ciò e restituire tutto in mezzo. Se no? viene trovato, qualunque cosa venga dopo l'ultima posizione di. sarà la tua estensione di file. – Crono

+0

La sottostringa dovrebbe funzionare, assicurati di avere un account per le estensioni con una lunghezza maggiore di 3. – Neolisk

+0

sei tu quello che fornisce gli URL? Sono sul tuo sito o su siti di terze parti? –

risposta

6

E 'strano, ma funziona:

string url = @"http://example.com/file.jpg"; 
string ext = System.IO.Path.GetExtension(url); 
MessageBox.Show(this, ext); 

ma come ha osservato crono muggito, non funzionerà con i parametri:

string url = @"http://example.com/file.jpg?par=x"; 
string ext = System.IO.Path.GetExtension(url); 
MessageBox.Show(this, ext); 

risultato: ".jpg par = x"

+0

Non funzionerà con le query parametrizzate. – Crono

+0

sì, crono è giusto, non l'ho visto arrivare :) – heringer

3

Se si desidera ottenere la parte .jpg di http://example.com/file.jpg, utilizzare solo Path.GetExtension come suggerito da heringer.

// The following evaluates to ".jpg" 
Path.GetExtension("http://example.com/file.jpg") 

Se il link per il download è qualcosa di simile http://example.com/this_url_will_download_a_file quindi il nome del file sarà contenuto come parte del Content-Disposition, un'intestazione HTTP che viene utilizzata per suggerire un nome di file per i browser che visualizza una finestra di dialogo "salva file". Se si desidera ottenere il nome del file, è possibile utilizzare la tecnica suggerita da Get filename without Content-Disposition per avviare il download e ottenere le intestazioni HTTP, ma annullare il download, senza in realtà il download di qualsiasi file

HttpWebResponse res = (HttpWebResponse)request.GetResponse(); 
using (Stream rstream = res.GetResponseStream()) 
{ 
    string fileName = res.Headers["Content-Disposition"] != null ? 
     res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") : 
     res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) : 
     Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ? 
     Path.GetFileName(res.ResponseUri.ToString()) : defaultFileName; 
} 
res.Close(); 
0

So che questo è un vecchia domanda, ma può essere utile per le persone che vedono questa domanda.

L'approccio migliore per ottenere l'estensione dal nome del file all'interno di un url, anche con i parametri sono con regex.

È possibile utilizzare questo schema (non solo gli URL):

.+(\.\w{3})\?*.* 

Spiegazione:

.+  Match any character between one and infinite 
(...) With this you create a group, after you can use for getting string inside the brackets 
\.  Match the character '.' 
\w  Matches any word character equal to [a-zA-Z0-9_] 
\?* Match the character '?' between zero and infinite 
.*  Match any character between zero and infinite 

Esempio:

http://example.com/file.png 
http://example.com/file.png?foo=10 

But if you have an url like this: 

http://example.com/asd 
This take '.com' as extension. 

in modo da poter utilizzare un modello forte per gli URL come this:

.+\/{2}.+\/{1}.+(\.\w+)\?*.* 

Spiegazione:

.+  Match any character between one and infinite 
\/{2}  Match two '/' characters 
.+  Match any character between one and infinite 
\/{1}  Match one '/' character 
.+  Match any character between one and infinite 
(\.\w+) Group and match '.' character and any word character equal to [a-zA-Z0-9_] from one to infinite 
\?*  Match the character '?' between zero and infinite 
.*  Match any character between zero and infinite 

Esempio:

http://example.com/file.png   (Match .png) 
https://example.com/file.png?foo=10 (Match .png) 
http://example.com/asd    (No match) 
C:\Foo\file.png      (No match, only urls!) 

http://example.com/file.png 

    http:  .+ 
    //   \/{2} 
    example.com .+ 
    /   \/{1} 
    file   .+ 
    .png   (\.\w+) 

Bye

Problemi correlati