代码比较山寨,如下: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.Threading;
using System.Collections;namespace picture
{
    public partial class ftpUpload : Form
    {
        //服务器ip
        string ftpIp = "192.168.4.88";
        //端口
        string port = "21";
        //用户名
        string userName = "wj";
        //密码
        string userPassword = "123456";
        //线程数量
        static int threadNum = 10;
        //定义目标路径
        const string picTargetPath = "/tempUpload/phototest";
        const string fileTargetPath = "/tempUpload/photoinfotest";
        //进度条中需要减去标牌的数量
        int minuend = 0;
        int success = 0;
        int fail = 0;
        //0表示未用过,1表示已用过
        int tag = 0;
        //存放图片的集合
        ArrayList picList = new ArrayList();
        //文件的存放目录
        string fileName = "";
        private static int MAX_TIMES = 3;        //文件上传失败保存信息的路径
        static string path = Info.Deal + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt";
        //保存图片信息的文件路径
        static string filePath = Info.Path + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt";        StreamWriter s = File.CreateText(path);
        StreamWriter sw = File.CreateText(filePath);        public ftpUpload(ArrayList list,string fileName)
        {
            InitializeComponent();
            this.picList = list;
            this.fileName = fileName;
        }        //当前进度条的值
        public int currentValue = 0;
        //显示进度条的委托声明
        delegate void ShowProgressDelegate(int totalStep, int currentStep);
        //显示进度条
        void ShowProgress(int totalStep, int currentStep)
        {
            if (progressBar1.InvokeRequired)
            {
                ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);                //为了避免工作线程被阻塞,采用异步调用委托
                this.BeginInvoke(showProgress, new object[] { totalStep, currentStep });
            }
            else
            {
                progressBar1.Maximum = totalStep;
                progressBar1.Value = currentStep;
            }        }
        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="targetPath"></param>如:/phototest
        /// <returns></returns>
        private FtpStatusCode UploadFun(string fileName,string targetPath)
        {            
            Stream requestStream = null;
            FileStream fileStream = null;
            FtpWebResponse uploadResponse = null;            //显示原文件路径
            //this.Invoke((EventHandler)delegate { label2.Text = fileName; });
            
 
            //构造目标路径
            FileInfo fileInf = new FileInfo(fileName);
            string uploadUrl = "ftp://" + ftpIp + ":" + port + targetPath + "/" + fileInf.Name;            try
            {
                //连接ftp服务器
                FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uploadUrl);
                uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
                uploadRequest.Proxy = null;
                NetworkCredential nc = new NetworkCredential();
                nc.UserName = userName;
                nc.Password = userPassword;
                uploadRequest.Credentials = nc;                //上传
                requestStream = uploadRequest.GetRequestStream();
                fileStream = File.Open(fileName, FileMode.Open);                byte[] buffer = new byte[1024];
                int bytesRead;
                while (true)
                {                    bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }
                }
                requestStream.Close();
                uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();                //如果是TXT格式就不用显示
                if (System.IO.Path.GetExtension(fileName).ToLower() == ".jpg")
                {
                    //显示图片
                    pictureBox1.Image = Image.FromStream(fileStream);
                }
                
                return uploadResponse.StatusCode;            }
            catch (UriFormatException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (uploadResponse != null)
                    uploadResponse.Close();
                if (fileStream != null)
                    fileStream.Close();
                if (requestStream != null)
                    requestStream.Close();            }
            return FtpStatusCode.Undefined;
        }        private void upLoadButton_Click(object sender, EventArgs e)
        {
            //分配每个线程传递照片数量
            int temp = picList.Count / threadNum;
            upLoadButton.Visible = false;
//创建10个线程上传照片
for (int i = 1; i < threadNum + 1; i++)
{
Thread t = new Thread(new ThreadStart(LoadUploadMain));
t.Name = (i * temp).ToString();
t.Start();
}
//开辟新的线程传递info文件和零散的照片
Thread th = new Thread(new ThreadStart(LoadUploadOthers));
th.Start();
        }我在前一个页面用ftpUpload ftp = new ftpUpload(picList, Info.Path);
                ftp.ShowDialog();调用,当网络异常,无法上传图片的时候,这个地方报异常“未处理的“System.Reflection.TargetInvocationException”类型的异常出现在 mscorlib.dll 中。其他信息: 调用的目标发生了异常。”代码只发了一部分。请高手帮忙啊,十分感谢。

解决方案 »

  1.   

            //测试添加多线程,传递图片,其代码和LoadUpload()类似
            private void LoadUploadMain()
            {
                //为使用线程,准备工作,保证每个线程去访问不同的资源
                int totalNum = picList.Count;//照片总数
                int temp = totalNum / threadNum;
                string name = Thread.CurrentThread.Name;
                int tempNum = Convert.ToInt32(name);            for (int i = tempNum - temp; i < tempNum; i++)
                {
                    //int big = 0, small = 0;
                    Picture pic = (Picture)picList[i];
                    //状态为不可用
                    if (pic.State.Equals("no"))
                    {
                        continue;
                    }
                    if (pic.Sign == "PLATE")
                    {
                        this.Invoke((EventHandler)delegate { minuend++; });
                        continue;
                    }
                    string smallPath = DateTime.Now.ToString("yyyyMMddhhmmss") + i.ToString() + "_small" + ".jpg";
                    ImageInfo.thumb(Info.Path + "\\" + pic.PhotoName, Info.Path + "\\" + smallPath, 100, 100, "gif");
                    pic.Thumb = smallPath;
                    //已经上传次数
                    int times = 0;
                    FtpStatusCode code = FtpStatusCode.Undefined;
                    //连接服务器失败时,且只能连接3次
                    while (times < MAX_TIMES && code == FtpStatusCode.Undefined)
                    {
                        code = UploadFun(fileName + "\\" + pic.PhotoName, picTargetPath);
                        times++;
                        ShowProgress((totalNum- minuend)*2, currentValue + 1);
                        currentValue++;
                    }
                    if (code == FtpStatusCode.Undefined)
                    {
                        big = 1;
                        //记录失败的个数
                        fail++;
                        //this.Invoke((EventHandler)delegate { label6.Text = fail.ToString(); });
                    }
                    else
                    {
                        //记录成功的个数
                        success++;
                        this.Invoke((EventHandler)delegate { label5.Text = success.ToString(); });
                    }
                    times = 0;                FtpStatusCode code2 = FtpStatusCode.Undefined;
                    while (times < MAX_TIMES && code2 == FtpStatusCode.Undefined)
                    {
                        code2 = UploadFun(fileName + "\\" + pic.Thumb, picTargetPath);
                        times++;
                        ShowProgress((totalNum - minuend) * 2, currentValue + 1);
                        currentValue++;
                    }
                    //上传缩略图成功时
                    if (code2 != FtpStatusCode.Undefined)
                    {
                        success++;
                        this.Invoke((EventHandler)delegate { label5.Text = success.ToString(); });
                        File.Delete(fileName + "\\" + pic.Thumb);
                    }
                    else
                    {
                        small = 1;
                        //记录失败的个数
                        fail++;
                        //this.Invoke((EventHandler)delegate { label6.Text = fail.ToString(); });
                    }                //大图与缩略图都上传成功
                    if (code != FtpStatusCode.Undefined && code2 != FtpStatusCode.Undefined)
                    {
                        lock (sw)
                        {
                            sw.WriteLine(pic.Fid + "," + pic.Cid + "," + pic.PhotoName + "," + smallPath + "," + pic.Description + "," + pic.OperId + "," + pic.Sid + ",|");
                            sw.Flush();
                        }
                    }
                    else
                    {                    lock (s)
                        {
                            s.WriteLine(pic.Fid + "," + pic.Cid + "," + fileName + "\\" + pic.PhotoName + "," + fileName + "\\" + smallPath + "," + pic.Description + "," + pic.OperId + "," + pic.Sid + ",all");
                            s.Flush();                    }
                    }
                }
            }
            /// <summary>
            /// 传递零散图片和info文件
            /// </summary>
            private void LoadUploadOthers()
            {
                //为使用线程,准备工作,保证每个线程去访问不同的资源
                int totalNum = picList.Count;//照片总数
                int start = totalNum - totalNum % threadNum;
                int end = totalNum;            for (int i = start; i < end; i++)
                {
                    //int big = 0, small = 0;
                    Picture pic = (Picture)picList[i];
                    //状态为不可用
                    if (pic.State.Equals("no"))
                    {
                        continue;
                    }
                    //如果是地标照片则不压缩,不上传
                    if (pic.Sign == "PLATE")
                    {
                        this.Invoke((EventHandler)delegate { minuend++; });
                        continue;
                    }
                    string smallPath = DateTime.Now.ToString("yyyyMMddhhmmss") + i.ToString() + "_small" + ".jpg";
                    ImageInfo.thumb(Info.Path + "\\" + pic.PhotoName, Info.Path + "\\" + smallPath, 100, 100, "gif");
                    pic.Thumb = smallPath;
                    //已经上传次数
                    int times = 0;
                    FtpStatusCode code = FtpStatusCode.Undefined;
                    //连接服务器失败时,且只能连接3次
                    while (times < MAX_TIMES && code == FtpStatusCode.Undefined)
                    {
                        code = UploadFun(fileName + "\\" + pic.PhotoName, picTargetPath);
                        times++;
                        ShowProgress((totalNum - minuend) * 2, currentValue + 1);
                        currentValue++;
                    }
                    if (code == FtpStatusCode.Undefined)
                    {
                        big = 1;
                        //记录失败的个数
                        fail++;
                        //this.Invoke((EventHandler)delegate { label6.Text = fail.ToString(); });
                    }
                    else
                    {
                        //记录成功的个数
                        success++;
                        this.Invoke((EventHandler)delegate { label5.Text = success.ToString(); });
                    }
                    times = 0;                FtpStatusCode code2 = FtpStatusCode.Undefined;
                    while (times < MAX_TIMES && code2 == FtpStatusCode.Undefined)
                    {
                        code2 = UploadFun(fileName + "\\" + pic.Thumb, picTargetPath);
                        times++;
                        ShowProgress((totalNum - minuend) * 2, currentValue + 1);
                        currentValue++;
                    }
                    //上传缩略图成功时
                    if (code2 != FtpStatusCode.Undefined)
                    {
                        success++;
                        this.Invoke((EventHandler)delegate { label5.Text = success.ToString(); });
                        File.Delete(fileName + "\\" + pic.Thumb);
                    }
                    else
                    {
                        small = 1;
                        //记录失败的个数
                        fail++;
                        //this.Invoke((EventHandler)delegate { label6.Text = fail.ToString(); });
                    }                //大图与缩略图都上传成功
                    if (code != FtpStatusCode.Undefined && code2 != FtpStatusCode.Undefined)
                    {
                        lock (sw)
                        {
                            sw.WriteLine(pic.Fid + "," + pic.Cid + "," + pic.PhotoName + "," + smallPath + "," + pic.Description + "," + pic.OperId + "," + pic.Sid + ",|");
                            sw.Flush();
                        }
                    }
                    else
                    {
                        lock (s)
                        {
                            s.WriteLine(pic.Fid + "," + pic.Cid + "," + fileName + "\\" + pic.PhotoName + "," + fileName + "\\" + smallPath + "," + pic.Description + "," + pic.OperId + "," + pic.Sid + ",all");
                            s.Flush();
                        }
                    }
                }
                int time = 0;
                FtpStatusCode code4 = FtpStatusCode.Undefined;
                while (time < MAX_TIMES && code4 == FtpStatusCode.Undefined && currentValue == (totalNum - minuend) * 2)
                {
                    sw.Close();
                    time++;
                    code4 = UploadFun(filePath, fileTargetPath);
                }        }
        }
    }
      

  2.   

    http://support.microsoft.com/kb/828991/zh-cnhttp://zhidao.baidu.com/question/127564794
      

  3.   

    已发现问题所在,就是进度条那边有问题,代码如下://当前进度条的值
            public int currentValue = 0;
            //显示进度条的委托声明
            delegate void ShowProgressDelegate(int totalStep, int currentStep);
            //显示进度条
            void ShowProgress(int totalStep, int currentStep)
            {
                if (progressBar1.InvokeRequired)
                {
                    ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);                //为了避免工作线程被阻塞,采用异步调用委托
                    this.BeginInvoke(showProgress, new object[] { totalStep, currentStep });
                }
                else
                {
                    progressBar1.Maximum = totalStep;
                    progressBar1.Value = currentStep;
                }        }
    后来不显示进度条,就没有那个问题,哪位高手能帮我改进下上面的代码。