¿Qué es una forma simple de descargar un archivo desde una ruta URL?¿Cómo descargar un archivo de una URL en C#?
Respuesta
Uso System.Net.WebClient.DownloadFile
:
string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
}
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}
La mejor solución pero me gustaría agregar 1 línea importante 'client.Credentials = new NetworkCredential ("UserName", "Password");' –
Un efecto secundario bienvenido: este método también admite archivos locales como primer parámetro – copa017
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
¡Bienvenido a SO! En general, no es una buena idea publicar una respuesta de baja calidad a una pregunta vieja y ya existente que ya tenga respuestas muy elevadas. – ThiefMaster
Encontré mi respuesta del comentario de seanb, pero realmente prefiero esta respuesta de "baja calidad" sobre las demás. Está completo (uso de declaraciones), conciso y fácil de entender. Ser una vieja pregunta es irrelevante, en mi humilde opinión. – Josh
Pero creo que la respuesta con el uso es mucho mejor, porque, creo que el WebClient debe eliminarse después de su uso. Al ponerlo dentro, se asegura de que esté dispuesto. –
También puede utilizar el método DownloadFileAsync en la clase de cliente Web. Descarga a un archivo local el recurso con el URI especificado. Además, este método no bloquea el hilo de llamada.
muestra:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
Para más información:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
Incluir este espacio de nombres
using System.Net;
Descargar asincrónica y poner un ProgressBar para mostrar el estado de la descarga dentro de la interfaz de usuario propio hilo
private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync(new System.Uri("http://www.sayka.in/downloads/front_view.jpg"),
"D:\\Images\\front_view.jpg");
}
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
La pregunta pregunta por la forma más simple. Hacerlo más complicado no lo hace más simple. – Enigmativity
La mayoría de las personas preferiría una barra de progreso durante la descarga. Entonces, simplemente escribí la forma más sencilla de hacerlo. Esta podría no ser la respuesta pero cumple con el requisito de Stackoverflow. Eso es para ayudar a alguien. – Sayka
@Sayka Respuesta principal :-). La solución "muy" simple es una pesadilla para el usuario final, ya que el hilo de la interfaz de usuario está bloqueado. Esta debería ser la solución más simple. Cualquier cosa más simple es ingenuo y engañoso – TFD
Compruebe si hay una conexión de red utilizando GetIsNetworkAvailable()
para evitar crear archivos vacíos cuando no está conectado a una red.
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadFileAsync(new Uri("http://www.examplesite.com/test.txt"),
"D:\\test.txt");
}
}
clase completa para descargar un archivo mientras se imprime el estado a la consola.
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
class FileDownloader
{
private readonly string _url;
private readonly string _fullPathWhereToSave;
private bool _result = false;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);
public FileDownloader(string url, string fullPathWhereToSave)
{
if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
if (string.IsNullOrEmpty(fullPathWhereToSave)) throw new ArgumentNullException("fullPathWhereToSave");
this._url = url;
this._fullPathWhereToSave = fullPathWhereToSave;
}
public bool StartDownload(int timeout)
{
try
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWhereToSave));
if (File.Exists(_fullPathWhereToSave))
{
File.Delete(_fullPathWhereToSave);
}
using (WebClient client = new WebClient())
{
var ur = new Uri(_url);
// client.Credentials = new NetworkCredential("username", "password");
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadFileCompleted += WebClientDownloadCompleted;
Console.WriteLine(@"Downloading file:");
client.DownloadFileAsync(ur, _fullPathWhereToSave);
_semaphore.Wait(timeout);
return _result && File.Exists(_fullPathWhereToSave);
}
}
catch (Exception e)
{
Console.WriteLine("Was not able to download file!");
Console.Write(e);
return false;
}
finally
{
this._semaphore.Dispose();
}
}
private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.Write("\r --> {0}%.", e.ProgressPercentage);
}
private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
{
_result = !args.Cancelled;
if (!_result)
{
Console.Write(args.Error.ToString());
}
Console.WriteLine(Environment.NewLine + "Download finished!");
_semaphore.Release();
}
public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
{
return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
}
}
Uso:
static void Main(string[] args)
{
var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec);
Console.WriteLine("Done - success: " + success);
Console.ReadLine();
}
¿Podría explicar por qué está usando 'SemaphoreSlim' en este contexto? – mmushtaq
En lugar de descargar a un archivo local, puede convertir a un objeto flujo de bytes y la tienda como un BLOB varbinary (max) en SQL Server.
Dado que la tabla se ve así:
CREATE TABLE [dbo].[Documents](
[DocumentId] [int] IDENTITY(1,1) NOT NULL,
[DocumentTypeId] [int] NOT NULL,
[UploadedByMemberId] [int] NOT NULL,
[DocumentTitle] [nvarchar](200) NOT NULL,
[DocumentDescription] [nvarchar](2000) NULL,
[FileName] [nvarchar](200) NOT NULL,
[DateUploaded] [datetime] NOT NULL,
[ApprovedForUsers] [bit] NOT NULL,
[ApprovedByMemberId] [int] NOT NULL,
[ApprovedDate] [datetime] NULL,
[DocBLOB] [varbinary](max) NOT NULL,
CONSTRAINT [PK_Documents] PRIMARY KEY CLUSTERED
(
[DocumentId] ASC
)
SqlParameter Title = new SqlParameter("@Title", SqlDbType.VarChar);
SqlParameter FileName = new SqlParameter("@FileName", SqlDbType.VarChar);
SqlParameter DateFileUploaded = new SqlParameter("@DateUploaded", SqlDbType.VarChar);
SqlParameter DocBLOB = new SqlParameter("@DocBLOB", SqlDbType.VarBinary);
command.Parameters.Add(Title);
command.Parameters.Add(FileName);
command.Parameters.Add(DateFileUploaded);
command.Parameters.Add(DocBLOB);
myStringWebResource = remoteUri + dataReader["FileName"].ToString();
imgdownload = myWebClient.DownloadData(myStringWebResource);
querySQL = @"INSERT INTO Documents(DocumentTypeId, UploadedByMemberId, DocumentTitle, DocumentDescription, FileName, DateUploaded, ApprovedForUsers, ApprovedByMemberId, ApprovedDate, DocBLOB) VALUES(1, 0, @Title, '', @FileName, @DateUploaded, 1, 0, GETDATE(), @DocBLOB);";
Title.Value = dataReader["Title"].ToString().Replace("'", "''").Replace("\"", "");
FileName.Value = dataReader["FileName"].ToString().Replace("'", "''").Replace("\"", "");
DateFileUploaded.Value = dataReader["DateUploaded"].ToString();
DocBLOB.Value = imgdownload;
command.CommandText = querySQL;
command.ExecuteNonQuery();
Es posible que necesite conocer el estado y actualizar un ProgressBar durante la descarga de archivos o utilizar credenciales antes de realizar la consulta.
Aquí está, un ejemplo que cubre estas opciones. Lambda notación y cadena de interpolación se ha utilizado:
using System.Net;
// ...
using (WebClient client = new WebClient()) {
Uri ur = new Uri("http://remotehost.do/images/img.jpg");
//client.Credentials = new NetworkCredential("username", "password");
String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
client.DownloadProgressChanged += (o, e) =>
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (o, e) =>
{
Console.WriteLine("Download finished!");
};
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}
A continuación código contienen la lógica de descarga de archivos con el nombre original
private string DownloadFile(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
string filename = "";
string destinationpath = Environment;
if (!Directory.Exists(destinationpath))
{
Directory.CreateDirectory(destinationpath);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result)
{
string path = response.Headers["Content-Disposition"];
if (string.IsNullOrWhiteSpace(path))
{
var uri = new Uri(url);
filename = Path.GetFileName(uri.LocalPath);
}
else
{
ContentDisposition contentDisposition = new ContentDisposition(path);
filename = contentDisposition.FileName;
}
var responseStream = response.GetResponseStream();
using (var fileStream = File.Create(System.IO.Path.Combine(destinationpath, filename)))
{
responseStream.CopyTo(fileStream);
}
}
return Path.Combine(destinationpath, filename);
}
Trate de usar esto:
private void downloadFile(string url)
{
string file = System.IO.Path.GetFileName(url);
WebClient cln = new WebClient();
cln.DownloadFile(url, file);
}
- 1. Descargar archivo de URL a una cadena
- 2. Descargar archivo usando libcurl en C/C++
- 3. ¿Cómo descargar un archivo con WinHTTP en C/C++?
- 4. Descargar el archivo url de datos
- 5. cómo descargar un archivo en java?
- 6. Descargar un archivo con VBS
- 7. ¿Cómo puedo descargar un archivo XML usando C#?
- 8. Descargar/Transmitir archivo desde la URL - asp.net
- 9. Cómo descargar mediante programación un archivo grande en C#
- 10. Descargar archivo Curl con url var
- 11. cómo descargar un solo archivo con varios subprocesos en C#
- 12. C#: descargar una URL con tiempo de espera
- 13. ¿Cómo puedo descargar un archivo desde una URL y guardarlo en Rails?
- 14. ¿Cómo descargar un archivo con MSYS?
- 15. Descargar un archivo en D
- 16. ¿Cómo descargar un archivo a una ruta específica desde una url determinada en un formulario de Windows?
- 17. ¿Cómo puedo descargar un archivo de EC2
- 18. Descargar un archivo usando Javascript
- 19. ¿Mejor manera de descargar un archivo binario?
- 20. Descargar archivo dentro de WebView
- 21. Descargar un archivo mediante programación en Android
- 22. Descargar un archivo con Emacs Lisp
- 23. ¿Cómo descargar una imagen de una URL a un directorio local?
- 24. Uso de Java para descargar archivos desde una URL HTTPS
- 25. ¿Cómo descargar un archivo en una cadena con una devolución de llamada de progreso?
- 26. Descargar un archivo con Adobe AIR
- 27. Descargar archivo único
- 28. ¿Cómo puedo descargar dinámicamente un archivo javascript?
- 29. jquery descargar un archivo en devolución de llamada
- 30. Python: Cómo descargar un archivo zip
Tener una mirada en System.Net.WebClient – seanb