文系エンジニアのぐん(@gunjiblog)です!
C#で対象のURLのファイルをダウンロードするアプリを作ってみたので、ソースコードを載せたいと思います!
C#初心者なので、間違いなどあったら教えてください!
動作確認済みです。
ダウンロード対象パスをtextBox1に、保存先パスをtextBox2に入力してGetを押す。
すると保存先パスに対象のファイルがダウンロードされるアプリです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.IO; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string textValue1 = textBox1.Text; string textValue2 = textBox2.Text; WebClient wc = new WebClient(); if (File.Exists(textValue2)) { MessageBox.Show(textValue2 + "は既に存在します。"); } try { Uri u = new Uri("http://~"); wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler(Download_complete); wc.DownloadDataAsync(u); } catch (WebException ex) { MessageBox.Show("ネットに接続されていません。"); } } private void Download_complete(object sender, DownloadDataCompletedEventArgs e) { try { byte[] data = e.Result; FileStream fs = new FileStream(@"C:\work\img.jpg", FileMode.Create); fs.Write(e.Result, 0, e.Result.Length); fs.Close(); textBox1.Text += "ファイルを保存しました。\r\n"; } catch (WebException exc) { textBox1.Text += exc.Message + "\r\n"; } } } } |