@@ -272,33 +272,53 @@ public static double GetFileSize(Uri? url)
272272
273273 public static async Task < long > GetFileSizeAsyncAsLong ( Uri ? url )
274274 {
275- if ( url is null )
275+ if ( url is null ) return 0 ;
276+
277+ try
278+ {
279+ using HttpClient client = new ( CoreTools . GenericHttpClientParameters ) ;
280+ HttpResponseMessage response = await client . SendAsync ( new HttpRequestMessage ( HttpMethod . Head , url ) ) ;
281+ return response . Content . Headers . ContentLength ?? 0 ;
282+ }
283+ catch ( Exception e )
276284 {
277- return 0 ;
285+ Logger . Warn ( $ "Could not load file size for url={ url } ") ;
286+ Logger . Warn ( e ) ;
278287 }
279288
289+ return 0 ;
290+ }
291+
292+ public static string GetFileName ( Uri url )
293+ {
280294 try
281295 {
282- #pragma warning disable SYSLIB0014 // Type or member is obsolete
283- WebRequest req = WebRequest . Create ( url ) ;
284- #pragma warning restore SYSLIB0014 // Type or member is obsolete
285- req . Method = "HEAD" ;
286- WebResponse resp = await req . GetResponseAsync ( ) ;
287- if ( long . TryParse ( resp . Headers . Get ( "Content-Length" ) , out long ContentLength ) )
296+ var handler = CoreTools . GenericHttpClientParameters ;
297+ handler . AllowAutoRedirect = false ;
298+ using HttpClient client = new ( handler ) ;
299+ HttpResponseMessage response = client . Send ( new HttpRequestMessage ( HttpMethod . Head , url ) ) ;
300+
301+ if ( response . StatusCode is HttpStatusCode . Moved or HttpStatusCode . Redirect
302+ or HttpStatusCode . RedirectMethod or HttpStatusCode . TemporaryRedirect
303+ or HttpStatusCode . PermanentRedirect )
288304 {
289- return ContentLength ;
305+ return GetFileName ( response . Headers . Location ??
306+ throw new HttpRequestException ( "A redirect code was returned but no new location was given" ) ) ;
290307 }
291308
309+ return response . Content . Headers . ContentDisposition ? . FileName ?? Path . GetFileName ( url . LocalPath ) ;
292310 }
293311 catch ( Exception e )
294312 {
295- Logger . Warn ( $ "Could not load file size for url= { url } ") ;
313+ Logger . Warn ( $ "Failed to retrieve file name for URL: { url } ") ;
296314 Logger . Warn ( e ) ;
315+ return string . Empty ;
297316 }
298-
299- return 0 ;
300317 }
301318
319+ public static Task < string > GetFileNameAsync ( Uri url )
320+ => Task . Run ( ( ) => GetFileName ( url ) ) ;
321+
302322
303323 public struct Version : IComparable
304324 {
0 commit comments