반응형


폼디자인

소스.

/*

 * 2014.03.10

 * 티스토리 블로그등에 분할 압축되어 올라온 파일들을 일괄다운로드 하기위해 만든 프로그램

 */

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.IO;

using System.Text.RegularExpressions;

using System.Diagnostics;

using System.Threading;


namespace FileDownloader

{

    public partial class Form1 : Form

    {

        private int maxFile = 0;


        public Form1()

        {

            InitializeComponent();

        }

        /// <summary>

        /// 인터넷 html에서 다운로드 받을 수 있는 파일을 불러와서 목록으로 만든다.

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnLoad_Click(object sender, EventArgs e)

        {

            if (txtURL.Text.Trim() != "")

            {

                if (dgFiles.Rows.Count > 0)

                {

                    dgFiles.Rows.Clear();

                }

                //01.경로에서 html소스가져오기

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(txtURL.Text.Trim());

                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

                StreamReader sr = new StreamReader(res.GetResponseStream());

                string html = sr.ReadToEnd();

                

                //02.html에서 <a>...</a>로 묶인 태그 뽑아내기 

                MatchCollection m1 = Regex.Matches(html, @"<a.*?>.*?</a>", RegexOptions.Singleline);

                

                foreach (Match m in m1)

                {

                    string value = m.Groups[0].Value;

                    for (int i = 0; i < value.Length; i++)

                    {

                        if(value.Substring(i,1) == ">")

                        {

                            bool chk = false;


                            //03.파일명(실제파일명과 링크명이 다를 수 있다.)

                            string filename = value.Substring(i + 1, value.Length - i - 1).Replace("</a>", "");

                            //04.티스토리브로그에서 파일다운로드시 이미지링크가 있는경우가 있어서 이를 우회하기 위한 태그

                            

                            if (txtFilter.Text.Trim() == "" || filename.Replace(txtFilter.Text.Trim(), "") != filename)

                            {

//필터링할 단어가 없으면 전체 </a>태그를 보여주고 필터링과 일치할 경우일치하는 일부</a>태그들을 보여준다.

                                if (txtFilter.Text.Trim() != "")

                                {

                                    for (int j = 0; j < filename.Length; j++)

                                    {

                                        if (filename.Substring(j, 1) == ">")

                                        {

                                            filename = filename.Substring(j + 1, filename.Length - j - 1);

                                            j = filename.Length;

                                            chk = true;

                                        }

                                    }

                                }

                                else

                                {

                                    chk = true;

                                }

                                if (chk == true)

                                {

                                    for (int j = 0; j < filename.Length; j++)

                                    {

                                        if (filename.Substring(j, 1) == ">")

                                        {

                                            filename = filename.Substring(j + 1, filename.Length - j - 1);

                                            break;

                                        }

                                    }

                                    DataGridViewRow row = (DataGridViewRow)dgFiles.Rows[0].Clone();

                                    row.Cells[0].Value = true;

                                    row.Cells[1].Value = filename;


                                    MatchCollection m2 = Regex.Matches(value, @"href=\""(.*?)\""", RegexOptions.Singleline);

                                    foreach (Match n in m2)

                                    {

                                        //href=태그 검출

                                        string value2 = n.Groups[1].Value;

                                        row.Cells[2].Value = value2;

                                    }


                                    dgFiles.Rows.Add(row);

                                    i = value.Length;

                                }

                            }

                        }

                    }

                }

            }

            else

            {

                MessageBox.Show("URL이 없습니다.");

            }

        }

        /// <summary>

        /// 다운받을 경로변경

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnPath_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog dig = new FolderBrowserDialog();

            if (dig.ShowDialog() == DialogResult.OK)

            {

                txtDown.Text = dig.SelectedPath;

            }

        }

        /// <summary>

        /// 다운로드시작

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnDown_Click(object sender, EventArgs e)

        {

            maxFile = 0;

            for (int i = 0; i < dgFiles.Rows.Count - 1; i++)

            {

                if ((bool)dgFiles.Rows[i].Cells[0].Value == true)

                {

                    maxFile++;

                }

            }

            proTotal.Style = ProgressBarStyle.Continuous;

            proTotal.Minimum = 0;

            proTotal.Maximum = maxFile;

            proTotal.Step = 1;

            proTotal.Value = 0;


            Thread th = new Thread(down_start);

            th.Start();

        }

        

        delegate void probarCall(int val);

        delegate void enableCtrl(Control btn, bool chk);

        int cntfile = 0;


        /// <summary>

        /// 컨트롤 활성/비활성

        /// 멀티스레드를 활용하므로 다운로드 중에 다른 버튼들을 클릭하지 않도록 한다.

        /// </summary>

        /// <param name="chk"></param>

        private void ctlEnables(bool chk)

        {

            string[] aryCtl = { "btnAll", "btnAll2", "btnLoad", "btnPath", "btnDown", "btnAll", "btnAll2", "txtURL", "txtDown", "txtFilter", "dgFiles" };

            for (int i = 0; i < aryCtl.Length; i++)

            {

                Control[] ctl = Controls.Find(aryCtl[i], false);

                ctl[0].Invoke(new enableCtrl(enable_control), new object[] { ctl[0], chk });

            }

        }

        /// <summary>

        /// 다운로드 시작

        /// </summary>

        private void down_start()

        {

            for (int i = 0; i < dgFiles.Rows.Count - 1; i++)

            {

                if ((bool)dgFiles.Rows[i].Cells[0].Value == true)

                {

                    maxFile++;

                }

            }


            if (maxFile > 0)

            {

                string[] dirs = txtDown.Text.Trim().Split('\\');

                string _dir = "";

                for (int i = 0; i < dirs.Length; i++)

                {

                    if (i == 0)

                    {

                    }

                    else

                    {

                        _dir = _dir + "\\" + dirs[i];


                        DirectoryInfo di = new DirectoryInfo(_dir);

                        if (!di.Exists)

                        {

                            di.Create();

                        }

                    }

                }


                ctlEnables(false);

                WebClient client = new WebClient();

                for (int i = 0; i < dgFiles.Rows.Count - 1; i++)

                {

                    if ((bool)dgFiles.Rows[i].Cells[0].Value == true)

                    {

                        try

                        {

                            string file = dgFiles.Rows[i].Cells[2].Value.ToString();

                            client.DownloadFile(file, txtDown.Text + "\\" + dgFiles.Rows[i].Cells[1].Value.ToString());

                            cntfile++;

                            proTotal.Invoke(new probarCall(downing_per), new object[] { cntfile });

                        }

                        catch(Exception ex)

                        {

                            MessageBox.Show(ex.Message);

                        }

                    }

                }

                MessageBox.Show("다운로드 완료했습니다.");


                ctlEnables(true);

            }

            else

            {

                MessageBox.Show("다운로드 할 파일이 없습니다.");

            }

        }

        /// <summary>

        /// 멀티스레드 상태에서 컨트롤을 제어하기 위해 빼놓은 함수

        /// </summary>

        /// <param name="ctl"></param>

        /// <param name="chk"></param>

        private void enable_control(Control ctl, bool chk)

        {

            ctl.Enabled = chk;

        }

        

        /// <summary>

        /// 전체 파일 다운로드 진행정도

        /// </summary>

        /// <param name="var"></param>

        private void downing_per(int var)

        {

            proTotal.Value = var;

        }

        /// <summary>

        /// 전체파일 선택

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnAll_Click(object sender, EventArgs e)

        {

            for (int i = 0; i < dgFiles.Rows.Count - 1; i++)

            {

                dgFiles.Rows[i].Cells[0].Value = true;

            }

        }

        /// <summary>

        /// 전체파일 선택 취소

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnAll2_Click(object sender, EventArgs e)

        {

            for (int i = 0; i < dgFiles.Rows.Count - 1; i++)

            {

                dgFiles.Rows[i].Cells[0].Value = false;

            }

        }


        private void btnArea_Click(object sender, EventArgs e)

        {

            for (int i = 0; i < dgFiles.Rows.Count - 1; i++)

            {

                if (dgFiles.Rows[i].Selected == true)

                {

                    dgFiles.Rows[i].Cells[0].Value = true;

                }

            }

        }


        private void btnArea2_Click(object sender, EventArgs e)

        {

            for (int i = 0; i < dgFiles.Rows.Count - 1; i++)

            {

                if (dgFiles.Rows[i].Selected == true)

                {

                    dgFiles.Rows[i].Cells[0].Value = false;

                }

            }

        }

    }

}


-------------------------------------------------------------------------------------

기존에 만들었던 분할 파일 프로그램이 허접하여 새로 만들었다.

기능이 대단하지는 않고 연습/공부 겸 만들었으며 나중에 소스 참조용으로 올린다.

이프로그램에는 멀티스래드, WebClient, DataGridView등의 제어 관련된 부분이 포함되어 있다.

자주사용하지 않다보니 까먹게 되어서 소스를 통째로 올린다.



FileDownloader.zip


+ Recent posts