使用 FtpWebRequest 类并分配 BackgroundWorker 来上传文件。并且工作正常,但现在我想从目录及其子目录上传文件。
我创建了一个名为“FtpUploading”的组件,其中定义了私有 void 函数“FtpUploading_DoWork”
同样应该从 Windows 窗体应用程序调用...如果目录中有单个文件,则为工作文件,但如果有多个文件和子目录...它将不起作用。
private void FtpUploading_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
FtpSettings ftpDet = e.Argument as FtpSettings;
string UploadPath = String.Format("{0}/{1}{2}", ftpDet.Host, ftpDet.TargetFolder == "" ? "" : ftpDet.TargetFolder + "/", Path.GetFileName(ftpDet.SourceFile));
if (!UploadPath.ToLower().StartsWith("ftp://"))
UploadPath = "ftp://" + UploadPath;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
request.UseBinary = true;
request.UsePassive = ftpDet.Passive;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpDet.Username, ftpDet.Password);
long FileSize = new FileInfo(ftpDet.SourceFile).Length;
string mFileName = new FileInfo(ftpDet.SourceFile).Name;
string FileSizeDescription = GetFileSize(FileSize);
int ChunkSize = 4096, NumRetries = 0, MaxRetries = 50;
long SentBytes = 0;
byte[] Buffer = new byte[ChunkSize];
using (Stream requestStream = request.GetRequestStream())
{
using (FileStream fs = File.Open(ftpDet.SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
int BytesRead = fs.Read(Buffer, 0, ChunkSize);
while (BytesRead > 0)
{
try
{
if (bw.CancellationPending)
return;
requestStream.Write(Buffer, 0, BytesRead);
SentBytes += BytesRead;
string SummaryText = String.Format(mFileName + " => Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription);
bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText);
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.ToString());
if (NumRetries++ < MaxRetries)
{
fs.Position -= BytesRead;
}
else
{
throw new Exception(String.Format("Error occurred during upload, too many retries. \n{0}", ex.ToString()));
}
}
BytesRead = fs.Read(Buffer, 0, ChunkSize);
}
}
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
System.Diagnostics.Debug.WriteLine(String.Format("Upload File Complete, status {0}", response.StatusDescription));
}
public static string GetFileSize(long numBytes)
{
string fileSize = "";
if (numBytes > 1073741824)
fileSize = String.Format("{0:0.00} Gb", (double)numBytes / 1073741824);
else if (numBytes > 1048576)
fileSize = String.Format("{0:0.00} Mb", (double)numBytes / 1048576);
else
fileSize = String.Format("{0:0} Kb", (double)numBytes / 1024);
if (fileSize == "0 Kb")
fileSize = "1 Kb"; // min.
return fileSize;
}
//调用函数
private void recursiveDirectory(string dirPath, string uploadPath)
{
string[] files = Directory.GetFiles(dirPath, "*.*");
string[] subDirs = Directory.GetDirectories(dirPath);
foreach (string file in files)
{
if (this.ftpUploading1.IsBusy)
{
// this.ftpUploading1.CancelAsync();
// this.btnFtp.Text = "Upload";
Thread.Sleep(50);
break;
}
else
{
ftpSet.TargetFolder = uploadPath;
ftpSet.SourceFile = file;
this.toolStripProgressBar1.Visible = true;
this.ftpUploading1.RunWorkerAsync(ftpSet);
this.btnFtp.Text = "Cancel";
}
}
foreach (string subDir in subDirs)
{
ftpClient.createDirectory(uploadPath + "/" + Path.GetFileName(subDir));
recursiveDirectory(subDir, uploadPath + "/" + Path.GetFileName(subDir));
}
}