I have a button on the form if I click on the button then starting to check if the directory on FTP server exists or not, if not then the directory will be create. After this uploading the picture to the directory which was created before but it's causing a form freeze so I can't do nothing on the form for a few seconds.
--- Checking if the directory is exist & create it if not ---
private bool CreateFTPDirectory()
{
try
{
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://127.0.01" + txtDirName.Text));
requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
requestDir.Credentials = new NetworkCredential("username", "password");
requestDir.UsePassive = true;
requestDir.UseBinary = true;
requestDir.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
return true;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
response.Close();
return true;
}
else
{
response.Close();
return false;
}
}
}
--- Button click event (uploading the file) ---
private void btnApply_Click(object sender, EventArgs e)
{
CreateFTPDirectory(); /// calling the private bool CreateFTPDirectory
string imgname = "xyz.jpg";
System.Net.FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/" + txtDirName.Text + "/" + imgname);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
using (MemoryStream sourceStream = new MemoryStream())
{
PointF infoLocation = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2, 0);
string date = DateTime.UtcNow.ToString("dd.MM.yyyy");
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
using (Font arialFont = new Font("Arial", 10))
{
graphics.DrawString(date, arialFont, Brushes.Green, infoLocation);
}
bitmap.Save(sourceStream, ImageFormat.Jpeg);
using (System.IO.Stream requestStream = request.GetRequestStream())
{
sourceStream.Position = 0; sourceStream.CopyTo(requestStream);
}
}
}