using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Design;
using System.Threading;
using System.IO;
using System.Net;namespace 文件的上传和下载
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int oldx;
private int oldy;
private WebClient client = new WebClient();
private void Form1_Load(object sender, EventArgs e)
{
radiodownfile.Checked = true;
label5.Text = DateTime.Now.ToString();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.Cursor = Cursors.Hand;
oldx = MousePosition.X;
oldy = MousePosition.Y;
}
} private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.SetDesktopLocation(this.Location.X + MousePosition.X - oldx, this.Location.Y + MousePosition.Y - oldy);
oldx = MousePosition.X;
oldy = MousePosition.Y;
}
} private void Form1_MouseUp(object sender, MouseEventArgs e)
{
this.Cursor = Cursors.Default; } private void label4_Click(object sender, EventArgs e)
{
Application.Exit();
} private void btnopen_Click(object sender, EventArgs e)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.ShowDialog();
if (openfile.FileName != null)
{
txturladdress.Text = openfile.FileName;
} } private void downfile()
{
string url = txturladdress.Text;
int n = url.LastIndexOf('\\');
string urladdress = url.Substring(0, n);
string filename = url.Substring(n + 1, url.Length -n- 1);
string dir = txtfilename.Text;
string path = dir + "\\" + filename;
try
{
WebRequest request = WebRequest.Create(urladdress);
}
catch (WebException exp)
{
MessageBox.Show(exp.Message + "Error!");
}
try
{
client.DownloadFile(urladdress, path);
}
catch (WebException exp)
{
MessageBox.Show(exp.Message + "Error!");
}
} private void upfile()
{
string url=txturladdress.Text;
string path=txtfilename.Text;
try
{
client.UploadFile(url,"post",path);
}
catch(WebException exp)
{
MessageBox.Show(exp.Message+"Error!");
} } private void btnstart_Click(object sender, EventArgs e)
{
if (radiodownfile.Checked && txtfilename.Text != null)
{
Thread th = new Thread(new ThreadStart(downfile));
th.Start();
MessageBox.Show("文件下载成功!");
}
if (radioupfile.Checked && txtfilename.Text != null)
{
Thread th = new Thread(new ThreadStart(upfile));
th.Start();
MessageBox.Show("文件上传成功!");
}
}
}
}程序无误,运行后,输入本地的资源和给定本地的保持路径。
到目标文件夹里去看没有上传和下载的资源文件。
不知道为什么,请大家帮我看一下,谢谢了
WebClient.UploadFile 方法
public byte[] UploadFile (
string address,
string fileName
)
WebClient myWebClient = new WebClient();
myWebClient.Credentials =new NetworkCredential(username,password);
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);WebClient wc = new WebClient();
Byte[] bytes = wc.DownloadData("");
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
fs.Write(bytes, 0, bytes.Length);
}
谢谢了!
qq:[email protected]
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections;namespace 简易系统
{
public partial class 抓取部分 : Form
{
private Hashtable glossary = new Hashtable();
private System.ComponentModel.Container comp = null;
public struct param
{
public int num;
public string url;
}
public delegate void listView1AddImg(string imgname, int num);
listView1AddImg myDelegate;
public 抓取部分()
{
InitializeComponent();
this.imageList1.ImageSize = new Size(130, 130);
this.listView1.LargeImageList = this.imageList1;
myDelegate = new listView1AddImg(listView1AddImgMethod); }
/// <summary>
/// 用hashtable实现的函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BuildGlo(Hashtable g)
{
StreamReader infile;
string line;
string path = Application.StartupPath + @"mytest.txt";
string[] words;
infile = File.OpenText(path);
char[] delimiter = new char[] { '>' };
while(infile.Peek()!=-1)
{
line = infile.ReadLine();
words = line.Split(delimiter);
g.Add(words[0], words[1]);
}
infile.Close();
}
private void DisPlay(Hashtable g)
{
object[] words = new object[2000];
g.Keys.CopyTo(words, 0);
for (int i = 0; i <= words.GetUpperBound(0); i++)
if (!(words[i] == null))
listBox1.Items.Add((words[i]));
}
/// <summary>
/// //////////////////////////////////
private void button1_Click(object sender, EventArgs e)
{
this.listView1.Items.Clear();
string url = textBox1.Text;
if (!CheckURL_regx(url))
{
url=CheckHttp(url);
}
Thread mythread = new Thread(DownWork);
mythread.Start((object)url);
}
private void DownWork(object url)
{
// string temp = null;
string imaurl = null;
int num1 = 0;
param param1 = new param();
WebClient web1 = new WebClient();
byte[] data1 = web1.DownloadData((string)url);
string html = Encoding.Default.GetString(data1);
string pattern=@"(?<picture>http://[\w/\.,&=]*.jpg)";
MatchCollection mh = Regex.Matches(html, pattern, RegexOptions.IgnoreCase);
foreach(Match m in mh)
{
param1.num = num1;
num1++;
imaurl = m.Groups["picture"].ToString();
param1.url = imaurl;
ThreadPool.QueueUserWorkItem(new WaitCallback(work), (object)param1);
}
}
private void work(object list1)
{//下载图片至特定文件夹下,保存问为imgname
string imgname=null;
param param1=new param();
param1 = (param)list1;
if (CheckActiveURL(param1.url))
{
WebClient web1 = new WebClient();
imgname = param1.num.ToString() + ".jpg";
web1.DownloadFile(param1.url, Application.StartupPath + "\\" + imgname);
this.listView1.Invoke(this.myDelegate, new object[] { imgname, param1.num });
}
}
/// <summary>
/// 检验URL的正确性,如果不能响应,会抛出异常
/// </summary>
/// <param name="URL"></param>
/// <returns></returns>
private bool CheckActiveURL(string URL)
{
bool result=true;
try
{
WebRequest myreq = (HttpWebRequest)WebRequest.Create(URL);
WebResponse myresp = myreq.GetResponse();
myresp.Close();
}
catch (WebException ex)
{
if (ex.Status==WebExceptionStatus.ProtocolError)
{
Debug.WriteLine(((HttpWebResponse)ex.Response).StatusCode);
}
result = false;
}
return result;
}
/// <summary>
/// 添加图片至listview控件中
/// </summary>
/// <param name="img"></param>
/// <param name="num"></param>
public void listView1AddImgMethod(string img,int num)
{
try
{
this.imageList1.Images.Add(Image.FromFile(Application.StartupPath + "\\" + img));
this.listView1.Items.Add(img);
this.listView1.Items[num].ImageIndex=num;
Debug.WriteLine(num);
Debug.WriteLine(img); }
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
/// <summary>
/// //保存string字符串到文件中
/// </summary>
/// <param name="input"></param>
private void showFileStream(string input)
{
string path = Application.StartupPath + @"mytest.txt";
if (File.Exists(path))
{
File.Delete(path);
}
using(FileStream fs=File.Create(path))
{
addText(fs, input);
}
}
/// <summary>
/// 将string保存到filestream流中
/// </summary>
/// <param name="fs"></param>
/// <param name="input"></param>
private void addText(FileStream fs,string input)
{
byte[] info = new UTF8Encoding(true).GetBytes(input);
fs.Write(info, 0, info.Length);
}
/// <summary>
/// 抓取网页文件,包含jpg,html,bmp等链接文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
string temp = null;
int i = 1;
string availableURL = null;
WebClient web1 = new WebClient();
if (!CheckURL_regx(textBox1.Text))
{
availableURL=CheckHttp(textBox1.Text);
}
byte[] data1 = web1.DownloadData(availableURL);
string html = Encoding.Default.GetString(data1);
string pattern = @"(?<picture>http://[\w/\.,&=]*.(jpg|bmp|html)+)";
MatchCollection mh = Regex.Matches(html, pattern, RegexOptions.IgnoreCase);
foreach (Match m in mh)
{
temp += i.ToString()+">"+m.Groups["picture"].ToString() + "\n";
i++; }
label2.Text = "抓取到的网页数目为:"+mh.Count.ToString();
showFileStream(temp);//保存数据至文件中
}
/// <summary>
/// 使用string的方法将不符合规范的url添加上协议头
/// </summary>
/// <param name="originalURL"></param>
/// <returns></returns>
private string CheckHttp(string originalURL)
{
string temp = originalURL;
if(!originalURL.Contains("http")||!originalURL.Contains("https"))
temp=temp.Insert(0,"http://");
return temp;
}
/// <summary>
/// 使用正则表达式检验URL的合法性
/// </summary>
/// <param name="URL"></param>
/// <returns></returns>
private bool CheckURL_regx(string URL)
{
bool result = true;
string patt = @"^http://[\w/\.,&=?]*";
Regex reg = new Regex(patt,RegexOptions.IgnoreCase);
Match mh = reg.Match(URL);
if (!mh.Success)
{
result = false;
}
return result;
}
}
}
贴图片很累吧,用《Csdn收音机》截图功能轻松解决!