2008-12-14 36 views

Respuesta

17

Probablemente debería añadir un poco de comprobación de errores, etc, pero esto es probablemente la forma más fácil de hacerlo:

System.Uri address = new System.Uri("http://tinyurl.com/api-create.php?url=" + YOUR ADDRESS GOES HERE); 
System.Net.WebClient client = new System.Net.WebClient(); 
string tinyUrl = client.DownloadString(address); 
Console.WriteLine(tinyUrl); 
+0

¿Qué ensamblaje necesitamos usar para 'System.Net.Uri'? – user1509

+0

System.dll (vea http://msdn.microsoft.com/en-us/library/system.uri.aspx) – mcrumley

+0

entonces hay una corrección, es 'System.Uri' y no' System.Net.Uri' – user1509

10

Después de hacer algunas investigaciones más ... me topé con el siguiente código:

public static string MakeTinyUrl(string url) 
    { 
     try 
     { 
      if (url.Length <= 30) 
      { 
       return url; 
      } 
      if (!url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp")) 
      { 
       url = "http://" + url; 
      } 
      var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + url); 
      var res = request.GetResponse(); 
      string text; 
      using (var reader = new StreamReader(res.GetResponseStream())) 
      { 
       text = reader.ReadToEnd(); 
      } 
      return text; 
     } 
     catch (Exception) 
     { 
      return url; 
     } 
    } 

parece que puede hacer el truco.

4

Tenga en cuenta que si está utilizando una aplicación a gran escala, está conectando en una dependencia bastante específica al esquema URL/API de TinyURL. Tal vez tienen garantías acerca de su URL no cambia, pero vale la pena echarle un vistazo

+0

Gracias Paul ... un buen consejo! – mattruma

+3

Me aseguraré de dejar que Paul de hace seis años sepa –

-1

Esto es muy fácil en .Net usaremos la API Tiny URL para generar una pequeña URL.

para obtener más información, consulte el siguiente enlace.

http://www.freshcodehub.com/Article/38/convert-url-to-shorten-url-or-tiny-url-in-aspnet-with-c

public static string MakeTinyUrl(string Url) 
 
     { 
 
      try 
 
      { 
 
       if (Url.Length <= 12) 
 
       { 
 
        return Url; 
 
       } 
 
       if (!Url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp")) 
 
       { 
 
        Url = "http://" + Url; 
 
       } 
 
       var request = WebRequest.Create("Need to put tiny URL API" + Url); 
 
       var res = request.GetResponse(); 
 
       string text; 
 
       using (var reader = new StreamReader(res.GetResponseStream())) 
 
       { 
 
        text = reader.ReadToEnd(); 
 
       } 
 
       return text; 
 
      } 
 
      catch (Exception) 
 
      { 
 
       return Url; 
 
      } 
 
     }

Cuestiones relacionadas