How to download a file from a URL in C#?

2019-01-01 06:24发布

What is a simple way of downloading a file from a URL path?

11条回答
只若初见
2楼-- · 2019-01-01 06:56

Include this namespace

using System.Net;

Download Asynchronously and put a ProgressBar to show the status of the download within the UI Thread Itself

private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        wc.DownloadFileAsync (
            // Param1 = Link of file
            new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
            // Param2 = Path to save
            "D:\\Images\\front_view.jpg"
        );
    }
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar.Value = e.ProgressPercentage;
}
查看更多
冷夜・残月
3楼-- · 2019-01-01 06:56

Below code contain logic for download file with original name

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);
    }
查看更多
泪湿衣
4楼-- · 2019-01-01 06:59
using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
查看更多
无与为乐者.
5楼-- · 2019-01-01 07:02

Instead of downloading this to a local file, you can convert to a byte stream object and store as a varbinary(MAX) BLOB in SQL Server.

Given that your table looks like:

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();
查看更多
心情的温度
6楼-- · 2019-01-01 07:07

Try using this:

private void downloadFile(string url)
{
     string file = System.IO.Path.GetFileName(url);
     WebClient cln = new WebClient();
     cln.DownloadFile(url, file);
}
查看更多
萌妹纸的霸气范
7楼-- · 2019-01-01 07:12

Use 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);        
}
查看更多
登录 后发表回答