当多个文件上传的时候,需要依次队列形式一个个上传,当上传某个文件的时候,锁定进程,上传完毕再开启锁。
在主类中的上传按钮事件代码:
//获取openFileDialog控件选择的文件名数组(openFileDialog可多个文件选择)
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "";
try
{
this.openFileDialog1.ShowDialog();
path = this.openFileDialog1.FileNames; //获取openFileDialog控件选择的文件名数组
string strpath = "";
for (int y = 0; y < path.Length; y++)
{
strpath += path[y];
}
textBox1.Text = strpath;
}
catch
{
this.lbl_ftpStakt.Text = "请选择文件!";
}
} //上传按钮事件
private void button2_Click(object sender, EventArgs e)
{
this.lbl_ftpStakt.Visible = true; //设置上传信息标签可见
this.lbl_ftpStakt.Text = "连接服务器...";
try
{
for (i = 0; i < path.Length; i++)
{
filename = path[i].ToString();
//实例化事件类
myTest fo = new myTest(filename);
fo.startUpEvent+=new myTest.myUpEventsHandler(this.RunsOnWorkerThread); //注册事件
fo.mythreadStart(); //调用类的方法
FileInfo p = new FileInfo(path[i].ToString());
uploadSQL(p.Name); //上传到库
}
//label1.Text = "上传成功";
}
catch
{
string s="";
for (int x = i; x < path.Length; x++)
{
FileInfo file = new FileInfo(path[i].ToString());
s += file.Name + " ";
}
this.lbl_ftpStakt.Text = "上传失败";
MessageBox.Show(s.ToString()+" 上传失败","提示");
}
} //连接ftp上传
public void RunsOnWorkerThread(string _filename)
{
//阻塞线程
mt.WaitOne();
Interlocked.Increment(ref flag); //状态值+1
this.lbl_ftpStakt.Text = "连接服务器中...";
FileInfo fileInf = new FileInfo(_filename);
FtpWebRequest reqFTP;
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://210.82.***.***/" + fileInf.Name));
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential("record", "files");
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 指定数据传输类型
reqFTP.UseBinary = true;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
//long _length = fileInf.Length; /////////
// 缓冲大小设置为2kb
int buffLength = 2048; ////
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
// 每次读文件流的2kb
contentLen = fs.Read(buff, 0, buffLength);
int allbye = (int)fileInf.Length;
int startbye = 0;
this.myProgressControl.Maximum = allbye;
this.myProgressControl.Minimum = 0;
this.myProgressControl.Visible = true;
this.lbl_ftpStakt.Visible = true;
this.lbl_ftpStakt.Text = "服务器连接中...";
// 流内容没有结束
while (contentLen != 0)