Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธี Download ไฟล์จาก URL ใน C#

ใช้ Class WebClient ใน Namespace System.Net มี Method สำหรับ Download/Upload ไฟล์

WebClient client = new WebClient();
client.DownloadFile("url", "localPath");

ตัวอย่างดาวน์โหลดรูปภาพ

using System;
using System.Net;

namespace DemoApplication
{
    class Program
    {
        public static void Main()
        {
            string url = "https://example.com/image.jpg";
            string savePath = @"D:\Demo\FreeImages.jpg";
            
            WebClient client = new WebClient();
            client.DownloadFile(url, savePath);
            
            Console.WriteLine("Download completed!");
            Console.ReadLine();
        }
    }
}

โค้ดจะดาวน์โหลดไฟล์จาก URL และบันทึกที่ Path ที่ระบุ

หมายเหตุ: WebClient ใช้ WebRequest Class ใต้หลังคา รองรับ Protocol ต่างๆ (HTTP, HTTPS, FTP)