I have a function that sends files to an ftp, the first time I use it it works perfectly, however when I use it a second time it gets stuck on the line: using (Stream writer = ftpRequest.GetRequestStream ())
The full function code follows:
private void EnviarFTP(string CaminhoArquivoLocal, string CaminhoFTP, string NomeArquivoFTP)
{
FtpWebRequest ftpRequest;
FtpWebResponse ftpResponse;
string sURI = "ftp://" + txtFTPServer.Text + "/" + CaminhoFTP;
try
{
if (!CheckFileExistsFtp(sURI))
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(sURI));
ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
ftpRequest.Credentials = new NetworkCredential(txtFTPUser.Text, ftpPass);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(sURI + NomeArquivoFTP));
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.Credentials = new NetworkCredential(txtFTPUser.Text, ftpPass);
ftpRequest.Timeout = 10000000;
ftpRequest.ReadWriteTimeout = 10000000;
//Seleção do arquivo a ser enviado
FileInfo arquivo = new FileInfo(CaminhoArquivoLocal);
byte[] fileContents = new byte[arquivo.Length];
using (FileStream fr = arquivo.OpenRead())
{
fr.Read(fileContents, 0, Convert.ToInt32(arquivo.Length));
}
using (Stream writer = ftpRequest.GetRequestStream())
{
writer.Write(fileContents, 0, fileContents.Length);
}
//obtem o FtpWebResponse da operação de upload
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
ftpRequest = null;
}
catch (WebException webex)
{
txtMsg.Text += Environment.NewLine + "ERRO=> " + webex.Message;
}
}