C
Chocolade1972
Guest
In the library class project user control code i have this:
void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
UploadDirectoryToFtp(e.ClickedItem.Text);
}
}
private string UploadDirectoryToFtp(string directorytoupload)
{
return directorytoupload;
}
In this case its directories in directorytoupload there is a directory name i selected.
The first thing is that i need to upload the whole directory including sub directories and all files.
So on the ftp server i will have the directory and all files.
How to upload the directory and sub directories and files do i need to use recursive and add all the sub directories and files to a List<string> ?
Now the method return the directory name only.
In the windows forms project after im adding the dll to the toolbox and drag it to my form1 designer i see myh ard disk drives and all files like windows explorer. Then i select a directory right click and Upload:
In the form1 windows forms application i have a backgroundworker im starting it with a button click:
private void btnUpload_Click(object sender, EventArgs e)
{
if(this.ftpProgress1.IsBusy)
{
this.ftpProgress1.CancelAsync();
this.btnUpload.Text = "Upload";
}
else
{
FtpSettings f = new FtpSettings();
f.Host = this.txtHost.Text;
f.Username = this.txtUsername.Text;
f.Password = this.txtPassword.Text;
f.TargetFolder = this.txtDir.Text;
f.SourceFile = this.txtUploadFile.Text;
f.Passive = this.chkPassive.Checked;
try
{
f.Port = Int32.Parse(this.txtPort.Text);
}
catch { }
this.toolStripProgressBar1.Visible = true;
this.ftpProgress1.RunWorkerAsync(f);
this.btnUpload.Text = "Cancel";
}
}
And the upload class:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace FTP_ProgressBar
{
public partial class FtpProgress : BackgroundWorker
{
private long FileSize = 0;
private string FileSizeDescription;
public static string ConnectionError;
public static string ftp;
private FtpSettings f;
private FtpWebRequest ftpRequest;
private FtpWebResponse ftpResponse1;
public static DirectoryInfo d;
public static string[] files;
public static FileInfo[] dirflist;
private string rootDirectory = "root";
private string ftpcontentmaindirectory = @"c:\myftpdownloads";
private string ftpcontentdir;
private string hostDirectory = "ftp.newsxpressmedia.com";
private string UserName = "newsxpressmediacom";
private string Password = "Ynnad-1972";
private DateTime DownloadStart;
public FtpProgress()
{
InitializeComponent();
}
public FtpProgress(IContainer container)
{
DownloadStart = DateTime.Now;
ftpcontentdir = Path.Combine(ftpcontentmaindirectory, rootDirectory);
if (!Directory.Exists(ftpcontentdir))
Directory.CreateDirectory(ftpcontentdir);
container.Add(this);
InitializeComponent();
}
private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
{
//FileInfoUploadFiles(sender, e);
StringArrayUploadFiles(sender, e);
}
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";
return fileSize;
}
private void StringArrayUploadFiles(object sender, DoWorkEventArgs e)
{
try
{
foreach (string txf in files)
{
string fn = txf;
BackgroundWorker bw = sender as BackgroundWorker;
f = e.Argument as FtpSettings;
if (f.TargetFolder != "")
createDirectory(f.TargetFolder);
string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(fn));
if (!UploadPath.ToLower().StartsWith("ftp://"))
UploadPath = "ftp://" + UploadPath;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
request.UseBinary = true;
request.UsePassive = f.Passive;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = 300000;
request.Credentials = new NetworkCredential(f.Username, f.Password);
long FileSize = new FileInfo(fn).Length;//f.SourceFile).Length;
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(fn, 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("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));
}
//}
}
catch (WebException ex)
{
switch (ex.Status)
{
case WebExceptionStatus.NameResolutionFailure:
ConnectionError = "Error: Please check the ftp address";
break;
case WebExceptionStatus.Timeout:
ConnectionError = "Error: Timout Request";
break;
}
}
}
In the bottom:
public class FtpSettings
{
public string Host, Username, Password, TargetFolder, SourceFile;
public bool Passive;
public int Port = 21;
}
What i need it to do is two things.
First when i select the directory in the library class project it should collect all sub directories and all files if there are any in the selected directory. And add all of them to a List.
Second thing after selected the directory and collected all sub directories and files it should start the backgroundworker automatic and upload all the directory content to the ftp server. So in the end on my ftp server i will see the directory and inside the sub directories files...like it is on my hard disk.
Continue reading...
void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
UploadDirectoryToFtp(e.ClickedItem.Text);
}
}
private string UploadDirectoryToFtp(string directorytoupload)
{
return directorytoupload;
}
In this case its directories in directorytoupload there is a directory name i selected.
The first thing is that i need to upload the whole directory including sub directories and all files.
So on the ftp server i will have the directory and all files.
How to upload the directory and sub directories and files do i need to use recursive and add all the sub directories and files to a List<string> ?
Now the method return the directory name only.
In the windows forms project after im adding the dll to the toolbox and drag it to my form1 designer i see myh ard disk drives and all files like windows explorer. Then i select a directory right click and Upload:
In the form1 windows forms application i have a backgroundworker im starting it with a button click:
private void btnUpload_Click(object sender, EventArgs e)
{
if(this.ftpProgress1.IsBusy)
{
this.ftpProgress1.CancelAsync();
this.btnUpload.Text = "Upload";
}
else
{
FtpSettings f = new FtpSettings();
f.Host = this.txtHost.Text;
f.Username = this.txtUsername.Text;
f.Password = this.txtPassword.Text;
f.TargetFolder = this.txtDir.Text;
f.SourceFile = this.txtUploadFile.Text;
f.Passive = this.chkPassive.Checked;
try
{
f.Port = Int32.Parse(this.txtPort.Text);
}
catch { }
this.toolStripProgressBar1.Visible = true;
this.ftpProgress1.RunWorkerAsync(f);
this.btnUpload.Text = "Cancel";
}
}
And the upload class:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace FTP_ProgressBar
{
public partial class FtpProgress : BackgroundWorker
{
private long FileSize = 0;
private string FileSizeDescription;
public static string ConnectionError;
public static string ftp;
private FtpSettings f;
private FtpWebRequest ftpRequest;
private FtpWebResponse ftpResponse1;
public static DirectoryInfo d;
public static string[] files;
public static FileInfo[] dirflist;
private string rootDirectory = "root";
private string ftpcontentmaindirectory = @"c:\myftpdownloads";
private string ftpcontentdir;
private string hostDirectory = "ftp.newsxpressmedia.com";
private string UserName = "newsxpressmediacom";
private string Password = "Ynnad-1972";
private DateTime DownloadStart;
public FtpProgress()
{
InitializeComponent();
}
public FtpProgress(IContainer container)
{
DownloadStart = DateTime.Now;
ftpcontentdir = Path.Combine(ftpcontentmaindirectory, rootDirectory);
if (!Directory.Exists(ftpcontentdir))
Directory.CreateDirectory(ftpcontentdir);
container.Add(this);
InitializeComponent();
}
private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
{
//FileInfoUploadFiles(sender, e);
StringArrayUploadFiles(sender, e);
}
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";
return fileSize;
}
private void StringArrayUploadFiles(object sender, DoWorkEventArgs e)
{
try
{
foreach (string txf in files)
{
string fn = txf;
BackgroundWorker bw = sender as BackgroundWorker;
f = e.Argument as FtpSettings;
if (f.TargetFolder != "")
createDirectory(f.TargetFolder);
string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(fn));
if (!UploadPath.ToLower().StartsWith("ftp://"))
UploadPath = "ftp://" + UploadPath;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
request.UseBinary = true;
request.UsePassive = f.Passive;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = 300000;
request.Credentials = new NetworkCredential(f.Username, f.Password);
long FileSize = new FileInfo(fn).Length;//f.SourceFile).Length;
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(fn, 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("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));
}
//}
}
catch (WebException ex)
{
switch (ex.Status)
{
case WebExceptionStatus.NameResolutionFailure:
ConnectionError = "Error: Please check the ftp address";
break;
case WebExceptionStatus.Timeout:
ConnectionError = "Error: Timout Request";
break;
}
}
}
In the bottom:
public class FtpSettings
{
public string Host, Username, Password, TargetFolder, SourceFile;
public bool Passive;
public int Port = 21;
}
What i need it to do is two things.
First when i select the directory in the library class project it should collect all sub directories and all files if there are any in the selected directory. And add all of them to a List.
Second thing after selected the directory and collected all sub directories and files it should start the backgroundworker automatic and upload all the directory content to the ftp server. So in the end on my ftp server i will see the directory and inside the sub directories files...like it is on my hard disk.
Continue reading...