開発環境 |
Microsoft Visual Studio Express 2013 for Windows Desktop |
実行環境 |
Microsoft Windows 8.1 (64bit) |
プロジェクトの種類 |
Visual C#/Windows フォーム アプリケーション |
プロジェクト名 |
ImgFileDownloader |
コンテナー/Panel
(Name):panel1
プロパティ:Dock=Top/Size.Height=25
コンテナー/SplitContainer
(Name):splitContainer1
プロパティ:Orientation=Horizontal
コモン コントロール/TextBox
(Name):textBox1
コモン コントロール/Button
(Name):button1
プロパティ:Text=Navigate
コモン コントロール/Button
(Name):button2
プロパティ:Text=Download
- splitContainer1.Panel1に以下のコントロールを追加。
コモン コントロール/WebBrowser
(Name):webBrowser1
プロパティ:ScriptErrorsSuppressed=True
- splitContainer1.Panel2に以下のコントロールを追加。
コモン コントロール/TextBox
(Name):textBox2
プロパティ:Dock=Fill/Multiline=True/ScrollBars=Vertical
Form1
プロパティ:AcceptButton=button1
以下のイベントを追加。(プロパティのツールバーからイベントを選択)
panel1_Resize ※splitContainer1.Panel1ではない
button1_Click
webBrowser1_Navigated
button2_Click
Form1の大きさやsplitContainer1の分割線を適当に調節する。
Form1.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
namespace ImgFileDownloader
{
public partial class Form1 : Form
{
readonly List<string> extList = new List<string> { ".jpg", ".gif", ".png", ".jpeg" };
List<string> urlList;
public Form1()
{
InitializeComponent();
PanelResize();
textBox1.Text = "http://www.google.co.jp/";
}
void PanelResize()
{
button2.Left = panel1.Right - button2.Width;
button1.Left = button2.Left - button1.Width;
textBox1.Width = button1.Left;
}
private void panel1_Resize(object sender, EventArgs e)
{
PanelResize();
}
// Navigate
private void button1_Click(object sender, EventArgs e)
{
string urlString = textBox1.Text;
webBrowser1.Navigate(urlString);
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
Text = webBrowser1.Document.Title + " - ImgFileDownloader";
textBox1.Text = webBrowser1.Url.ToString();
urlList = new List<string>();
foreach (HtmlElement element in webBrowser1.Document.Links)
{
try
{
string path = element.GetAttribute("href");
Uri uri = new Uri(path);
path = uri.GetLeftPart(UriPartial.Path);
string ext = Path.GetExtension(path).ToLower();
if (extList.Contains(ext))
{
if (!urlList.Contains(path))
{
urlList.Add(path);
}
}
}
catch (System.Exception ex)
{
}
}
textBox2.Text = String.Join("\r\n", urlList);
textBox2.AppendText("\r\nCount=" + urlList.Count);
}
// Download
private void button2_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
textBox2.Text = "";
textBox2.HideSelection = false;
int count = 0;
foreach (string url in urlList)
{
string path = "C:\\picture\\" + Path.GetFileName(url); // 適当なディレクトリを指定する
textBox2.AppendText(String.Format("{0}/{1} {2}\r\n", ++count, urlList.Count, path));
if (!File.Exists(path))
{
try
{
wc.DownloadFile(url, path);
}
catch { }
for (int n = 0; n < 100; n++)
{
Application.DoEvents();
Thread.Sleep(10);
}
}
}
textBox2.AppendText("Complete: " + webBrowser1.Document.Title);
}
}
}
最終更新:2014年04月14日 13:58