async/await ftpupload damages uploaded file - c#

I am trying to ftpupload a zipfile with async/await pattern:
private async void button2_Click(object sender, RoutedEventArgs e)
{
await processFtp();
}
async Task processFtp()
{
string result = "";
string ftpHost = "ftp://mysite/mysubdir";
string ftpUser = "itsme";
string ftpPassword = "mypw";
string ftpfullpath = ftpHost + "/" + "OutdoorTest.zip";
string fileToUpload = #"c:\temp\Outdoorbilder.zip";
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpfullpath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUser,ftpPassword);
request.UseBinary = true;
request.KeepAlive = false;
request.ReadWriteTimeout = 1000000;
request.Timeout = 1000000;
using (Stream requestStream = request.GetRequestStream())
{
using (FileStream fs = File.OpenRead(fileToUpload))
{
byte[] b = new byte[10 * 1024];
int readLength = 0;
int sentLength = 0;
while ((readLength = fs.Read(b, 0, b.Length)) > 0)
{
await requestStream.WriteAsync(b, 0, b.Length);
int percentComplete = (int)((float)(sentLength += readLength) / (float)fs.Length * 100);
ftpprogress.Value = percentComplete;
}
requestStream.Close();
requestStream.Flush();
}
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
result = response.StatusDescription;
}
catch (WebException e)
{
result = e.Message;
if (e.Status == WebExceptionStatus.ProtocolError)
{
result = result + "Status Code : " +
((FtpWebResponse)e.Response).StatusCode;
result = result + "\nStatus Description : " +
((FtpWebResponse)e.Response).StatusDescription;
}
}
catch (Exception e)
{
result = e.Message;
}
MessageBox.Show(result);
}
}
The code seems to work fine and I get a 226 response. But the zip file on the ftp server is arround 1000bytes biger than the original and after download to a mobile android device cannot be opend/extracted.
When I upload without async/await pattern the uploaded file has the same size on ftp server as the local original.
How/where does this happen?

This has nothing to do with async/await.
Your problem is that you are not telling the correct size to upload. Look at these two lines:
while ((readLength = fs.Read(b, 0, b.Length)) > 0)
{
await requestStream.WriteAsync(b, 0, b.Length);
You need to specify that the WriteAsyc writes the read amount and not the amount allocated for the byte buffer. At least the last read will return less than the buffer size.
So the correct code is:
while ((bytesRead = fs.Read(b, 0, b.Length)) > 0)
{
await requestStream.WriteAsync(b, 0, bytesRead);

Related

FtpWebRequest FTP download with ProgressBar

My code works, but the ProgressBar jumps directly to 100% and the download will go on. When its finished then comes a messageBox to take a Info.
I have already changed the buffer size, but it doesn't matter.
What am I doing wrong here?
Here is my Code:
void workerDOWN_DoWork(object sender, DoWorkEventArgs e)
{
string fileFullPath = e.Argument as String;
string fileName = Path.GetFileName(fileFullPath);
string fileExtension = Path.GetExtension(fileName);
label4.Invoke((MethodInvoker)delegate { label4.Text = "Downloading File.."; });
string ftpServerIP = "XXX";
string ftpUserName = "XXX";
string ftpPassword = "XXX";
try
{
//Datei vom FTP Server downloaden
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "/" + fileName);
request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(fileFullPath))
{
var buffer = new byte[32 * 1024];
int totalReadBytesCount = 0;
int readBytesCount;
while ((readBytesCount = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, readBytesCount);
totalReadBytesCount += readBytesCount;
var progress = (int)((float)totalReadBytesCount / (float)fileStream.Length * 100);
workerDOWN.ReportProgress((int)progress);
label3.Invoke((MethodInvoker)delegate { label3.Text = progress + " %"; });
}
}
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
MessageBox.Show("Datei nicht gefunden!", "Error");
}
}
e.Result = fileFullPath;
}
void workerDOWN_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string fileFullPath = e.Result as String;
string fileName = Path.GetFileName(fileFullPath);
MessageBox.Show("Download erfolgreich!","Information");
progressBar1.Value = 0;
label3.Invoke((MethodInvoker)delegate { label3.Text = " "; });
label4.Invoke((MethodInvoker)delegate { label4.Text = " "; });
}
Trivial example of FTP download using FtpWebRequest with WinForms progress bar:
private void button1_Click(object sender, EventArgs e)
{
// Run Download on background thread
Task.Run(() => Download());
}
private void Download()
{
try
{
const string url = "ftp://ftp.example.com/remote/path/file.zip";
var credentials = new NetworkCredential("username", "password");
// Query size of the file to be downloaded
WebRequest sizeRequest = WebRequest.Create(url);
sizeRequest.Credentials = credentials;
sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;
int size = (int)sizeRequest.GetResponse().ContentLength;
progressBar1.Invoke(
(MethodInvoker)(() => progressBar1.Maximum = size));
// Download the file
WebRequest request = WebRequest.Create(url);
request.Credentials = credentials;
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(#"C:\local\path\file.zip"))
{
byte[] buffer = new byte[10240];
int read;
while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, read);
int position = (int)fileStream.Position;
progressBar1.Invoke(
(MethodInvoker)(() => progressBar1.Value = position));
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
The core download code is based on:
Upload and download a file to/from FTP server in C#/.NET
To explain why your code does not work:
You are using size of the target file for the calculation: fileStream.Length – It will always be equal to totalReadBytesCount, hence the progress will always be 100.
You probably meant to use ftpStream.Length, but that cannot be read.
Basically with FTP protocol, you do not know size of the file you are downloading. If you need to know it, you have to query it explicitly before the download. Here I use the WebRequestMethods.Ftp.GetFileSize for that.
i have now a solution thats work for me.
The Idea to get first the File Size was great.
But when i first makes an query to check the File Size, the Ftp Server throws a Error. Like this
FtpWebRequest error: 550 Size not allowed in ASCII mode
Now first i download a dummy file to open the Connection.. See below
Thanks to all for the Support.
Great Community. Thanks.
void workerDOWN_DoWork(object sender, DoWorkEventArgs e)
{
string fileFullPath = e.Argument as String;
string fileName = Path.GetFileName(fileFullPath);
string fileExtension = Path.GetExtension(fileName);
label4.Invoke((MethodInvoker)delegate { label4.Text = "Downloading File.."; });
//FTP Download und Delete
string ftpServerIP = "XXX";
string ftpUserName = "XXXX";
string ftpPassword = "XXXXX";
try
{
// dummy download ftp connection for ftp server bug
FtpWebRequest DummyRequest = (FtpWebRequest)WebRequest.Create(("ftp://" + ftpServerIP + "/anyfile"));
DummyRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
DummyRequest.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = DummyRequest.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(Path.GetDirectoryName(Application.ExecutablePath) + "\\anyfile"))
{
ftpStream.CopyTo(fileStream);
}
//delete downloaded test file
File.Delete(Path.GetDirectoryName(Application.ExecutablePath) + "\\anyfile");
// Query size of the file to be downloaded
FtpWebRequest sizeRequest = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "/" + fileName);
sizeRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;
var fileSize = sizeRequest.GetResponse().ContentLength;
//file download
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "/" + fileName);
request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(fileFullPath))
{
var buffer = new byte[32 * 1024];
int totalReadBytesCount = 0;
int readBytesCount;
while ((readBytesCount = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, readBytesCount);
totalReadBytesCount += readBytesCount;
var progress = (int)((float)totalReadBytesCount / (float)fileSize * 100);
workerDOWN.ReportProgress((int)progress);
label3.Invoke((MethodInvoker)delegate { label3.Text = progress + " %"; });
}
}
// delete file on ftp server
FtpWebRequest Delrequest = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "/" + fileName);
Delrequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
Delrequest.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse Delresponse = (FtpWebResponse)Delrequest.GetResponse();
Delresponse.Close();
// message file deleted
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("System: " + fileName + " wurde auf dem Server gelöscht." + Environment.NewLine); });
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
MessageBox.Show("Datei nicht gefunden!", "Error");
}
}
e.Result = fileFullPath;
}
void workerDOWN_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void workerDOWN_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string fileFullPath = e.Result as String;
string fileName = Path.GetFileName(fileFullPath);
MessageBox.Show("Download erfolgreich!","Information");
progressBar1.Value = 0;
label3.Invoke((MethodInvoker)delegate { label3.Text = " "; });
label4.Invoke((MethodInvoker)delegate { label4.Text = " "; });
}
Without knowing exactly what your code in the ProgressChanged eventhandler does, I think that you unintentionally put the brackets in your progress calculation after * 100.
You could try this:
var progress = (int)((float)totalReadBytesCount / (float)fileStream.Length) * 100;

JS: Call API from server side

The following JavaScript code is working fine on old i9 browser but not on the latest one. Now I want to call API from server side as this code is not working due to cross domain cores issue.
var xmlHttpDevice = new XMLHttpRequest();
xmlHttpDevice.open("DEVICEINFO", "http://127.0.0.1:" + PortNumber + "/getDeviceInfo", true);
xmlHttpDevice.onload = function (e) {
if (xmlHttpDevice.readyState === 4) {
if (xmlHttpDevice.status === 200) {
alert(xmlHttpDevice.responseText);
} else {
alert(xmlHttpDevice.statusText);
}
}
};
xmlHttpDevice.onerror = function (e) {
console.error(xmlHttpDevice.statusText);
};
var params = "rdverb=DEVICEINFO&URL=''";
xmlHttpDevice.send(params);
my server side code :
TcpClient socket = new TcpClient();
try
{
// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
string strPortNumber = string.Empty;
string strRDVerb = "";
int PortNumberStartRange = 11099;
result.AsyncWaitHandle.WaitOne();
if (context.Request.InputStream != null)
{
var body = new StreamReader(context.Request.InputStream).ReadToEnd();
GetPostedData(ref strPortNumber, ref strRDVerb, body);
}
else
{
strPortNumber = "12345";
strRDVerb = "RDSERVICE";
}
if (strRDVerb != "RDSERVICE" && strRDVerb != "DEVICEINFO")
{
strRDVerb = "CAPTURE";
}
//var body = new StreamReader(context.Request.InputStream).ReadToEnd();
string response = string.Empty;
//Get the stream that will be used to send/receive data
ExecuteRecoveryCode(ref socket, PortNumberStartRange);
NetworkStream ns = socket.GetStream();
//Write the HTTP Header info to the stream
StreamWriter sw = new StreamWriter(ns);
if (strRDVerb == "DEVICEINFO")
{
var message = "rdverb=DEVICEINFO&URL=''";
//var data = System.Text.Encoding.ASCII.GetBytes(message);
sw.Write(message, 0, message.Length);
sw.WriteLine(string.Format(strRDVerb + " /getDeviceInfo HTTP/1.1"));
sw.WriteLine(string.Format("HOST:127.0.0.1:11100"));
}
sw.Flush();
//Save the data that lives in the stream
string packet = string.Empty;
StreamReader sr = new StreamReader(ns);
int count = 0;
string EndString = string.Empty;
GetServiceMethod(strRDVerb, ref count, ref EndString);
for (int i = 0; i < count; i++)
{
packet = sr.ReadLine();
response += packet;
}
HttpListenerResponse resp = context.Response;
//byte[] buffer = System.Text.Encoding.UTF8.GetBytes("<HTML><BODY> " + response + EndString + "</BODY></HTML>");
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(response + EndString);
resp.StatusDescription = response;
resp.ContentLength64 = buffer.Length;
System.IO.Stream output = resp.OutputStream;
resp.StatusCode = (int)HttpStatusCode.OK;
output.Write(buffer, 0, buffer.Length);
output.Close();
resp.Close();
}
catch (Exception ex)
{
//throw ex;
}
finally
{
socket.Close();
listener.BeginGetContext(new AsyncCallback(OnRequestReceive), listener);
}

Http post method hanging before getting response using c# [duplicate]

Failed to get response for large file HTTP put create file using c#
I am using file watcher service service monitor, when user created file or folder we are uploading to cloud
if file size more than 512 MB it is taking too much time to get the response
here I am confusing here the issue with my code or server
and reason for this error
if any changes on my code suggest me.
{
var fileFolderObj1 = new FileFolder();
var postURL = apiBaseUri + "/filefolder/create/file/user/" + userId; // +"?type=file";
code = HttpStatusCode.OK;
HttpWebResponse response = null;
FileInfo f = new FileInfo(filePath);
long filesizeF = f.Length;
try
{
string selectedFile = null;
selectedFile = filePath;
var fi = System.IO.Path.GetFileName(filePath);
////commented for some reason
var postParameters = new Dictionary<string, object>();
postParameters.Add("file", new FileParameter(filePath, ""));
postParameters.Add("parentId", parentId);
postParameters.Add("newName", fi);
postParameters.Add("cloudId", cloudId);
postParameters.Add("isSecure", isSecure);
//postParameters.Add("fileSize", fi.Length);
postParameters.Add("fileSize", filesizeF);
var userAgent = "Desktop";
var formDataBoundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
var uri = new Uri(postURL);
var createFileRequest = WebRequest.Create(uri) as HttpWebRequest;
this.SetBasicAuthHeader(createFileRequest, userId, password);
createFileRequest.ContentType = "multipart/form-data";
createFileRequest.Method = "PUT";
createFileRequest.Timeout = System.Threading.Timeout.Infinite;
createFileRequest.KeepAlive = false;/*true;*/
createFileRequest.UserAgent = userAgent;
createFileRequest.CookieContainer = new CookieContainer();
try
{
using (var requestStream = createFileRequest.GetRequestStream())
{
}
using (response = (HttpWebResponse)createFileRequest.GetResponse())
{
StreamReader(response.GetResponseStream()).ReadToEnd();
fileFolderObj1 = JsonConvert.DeserializeObject<FileFolder>(reslut);
}
}
catch (Exception exc)
{
if (response != null)
{
code = response.StatusCode;
}
}
}
catch (Exception exc)
{
}
}
}
private static readonly Encoding encoding = Encoding.UTF8;
private void WriteMultipartFormData(Dictionary<string, object> postParameters, string boundary, Stream requestStream, ILogService logService = null)
{
var needsCLRF = false;
foreach (var param in postParameters)
{
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
{
requestStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
}
needsCLRF = true;
if (param.Value is FileParameter)
{
var fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
var header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
requestStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
FileStream fileStream = new FileStream(fileToUpload.FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0,buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
logService.Debug("WRITEMULTIPART FORM DATA Bufferlent Running :{0}", bytesRead);
}
fileStream.Close();
}
else
{
var postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
requestStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
var footer = "\r\n--" + boundary + "--\r\n";
requestStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
}
}

Remote server error: 150 Opening Binary mode data connection

I am trying to create a small console application that downloads files from a ftp server through Explicit FTP over TLS. I have create these applications before but i am getting an error with this one. I keep Getting this error:
The Remote Server returned an error: 150 Opening BINARY mode data connection fro "filename" <2000 bytes>.
I cant seem to figure out that to do, can anyone help me?
this is my code:
public void DownloadFiles(string fileName)
{
uri.Scheme = "ftp";
uri.Host = ftpUrl;
uri.Port = 21;
uri.UserName = username;
uri.Password = password;
uri.Path = "out";
try
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri.ToString() + "/" + fileName));
reqFTP.EnableSsl = true;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(username, password);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response;
response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
FileStream writeStream = new FileStream(localFolder + fileName, FileMode.Create);
long length = response.ContentLength;
int bufferSize = 2048;
Byte[] buffer = new Byte[bufferSize];
int readCount = responseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
writeStream.Write(buffer, 0, readCount);
readCount = responseStream.Read(buffer, 0, bufferSize);
}
AppendLogFile(response, "Downloading Files: ", fileName);
writeStream.Close();
responseStream.Close();
response.Close();
reqFTP.Abort();
}
catch (Exception ex)
{
Console.WriteLine("Error in DownloadFileByFileName method!! " + ex.Message);
}
}
thanks!
I could not find the solution for this so i when over to use Chillkat for this application. works fine. But needed to buy a year license.
this is my code:
public void Connect(string fileName)
{
bool success;
success = ftp.UnlockComponent("license");
if (!success)
{
Console.WriteLine(ftp.LastErrorText);
return;
}
ftp.IdleTimeoutMs = 10000;
ftp.AuthTls = true;
ftp.Ssl = false;
ftp.Hostname = ftpUrl;
ftp.Port = 21;
ftp.Username = username;
ftp.Password = password;
ftp.KeepSessionLog = true;
success = ftp.Connect();
if (success != true)
{
Console.WriteLine(ftp.LastErrorText);
return;
}
ftp.ClearControlChannel();
bool sucess = ftp.GetFile("out/" + fileName, localFolder + fileName);
if (!success)
{
Console.WriteLine(ftp.LastErrorText);
AppendErrorLogFile("Error in downloading file", "Download file method", fileName);
return;
}
else
{
AppendLogFile("Download Success", "Download File Method", fileName);
ftp.DeleteRemoteFile("out/" + fileName);
}
}
long length = response.ContentLength;
Is at fault here I believe, if you use this to download a file that already exists, your request will close before you can get a response from the server and throw the 150 error.

FtpWebRequest while writing to stream if network goes down then FTP Server gives access denied problem when tried to re upload

I am using FtpWebRequest to upload a file.
Facing a problem of which i am not getting solution.
While uploading a heavy file if network get disconnected then FTP server acquires lock on file being uploaded, now when user tries to re upload the same file then it get access denied error.
I have set TimeOut and ReadWriteTimeOut to 5 secs of FtpWebRequest on FTP Server it is 10 secs.
Even if i try to upload same file after an Hour then also same problem exist.
// Get the object used to communicate with the server.
request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + FtpInfo.FtpServer.Trim() + "/" + FtpInfo.FtpFolderPath.Trim() + "/" + FileName.Trim()));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Proxy = null;
// FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(FtpInfo.UserNameForFTP.Trim(), FtpInfo.PasswordForFTP.Trim());
request.UsePassive = FtpInfo.UsePassive;
request.KeepAlive = FtpInfo.KeepAlive;
request.Timeout = FtpInfo.TimeOut; //Milliseconds
request.UseBinary = true;
request.ReadWriteTimeout = FtpInfo.TimeOut; //Milliseconds
FileInfo fi = new FileInfo(SourceLocation);
long length = fi.Length;
BytesUploaded = length;
long uploadSize = 0;
if (chunks == 0)
{
chunks = 1024;
}
else
{
buffLength = chunks;
}
byte[] buff = new byte[buffLength];
int contentLen;
using (FileStream fs = fi.OpenRead())
{
using (Stream strm = request.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buffLength);
try
{
while (contentLen != 0)
{
Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate() { lblProgress.Content = "Uploading '" + FileName + "'......" + "Bytes Uploaded (" + uploadSize.ToString() + "/" + length.ToString() + ")"; });
strm.Write(buff, 0, contentLen);
uploadSize += contentLen;
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
}
catch (Exception ex)
{
if (strm!=null)
{
try
{
strm.Close();
}
catch
{
throw ex;
}
}
throw ex;
}
}
fs.Close();
}
try
{
//requestStream.Close(); -orignal
fi = null;
request=null;
}
catch { }
I don't know enough about your app (is the FTP upload on a separate thread for example) but try this:
bool DoneOK = false;
FtpWebRequest request = null;
FtpWebResponse response = null;
try {
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + FtpInfo.FtpServer.Trim() + "/" + FtpInfo.FtpFolderPath.Trim() + "/" + FileName.Trim()));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Proxy = null;
// FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(FtpInfo.UserNameForFTP.Trim(), FtpInfo.PasswordForFTP.Trim());
request.UsePassive = FtpInfo.UsePassive;
request.KeepAlive = FtpInfo.KeepAlive;
request.Timeout = FtpInfo.TimeOut; //Milliseconds
request.UseBinary = true;
request.ReadWriteTimeout = FtpInfo.TimeOut; //Milliseconds
long length = new FileInfo(SourceLocation).Length;
long uploadSize = 0;
if ( chunks < 1 )
chunks = 1024;
buffLength = chunks;
byte[] buff = new byte[buffLength];
int contentLen = 0;
string MSG = "";
using (FileStream fs = File.OpenRead (SourceLocation))
using (Stream strm = request.GetRequestStream())
{
while ((contentLen = fs.Read(buff, 0, buffLength)) > 0 )
{
MSG = "Uploading '" + FileName + "'......" + "Bytes Uploaded (" + uploadSize.ToString() + "/" + length.ToString() + ")";
string tmp_MSG = MSG;
Dispatcher.Invoke(DispatcherPriority.Normal, () => { lblProgress.Content = tmpMSG; });
strm.Write(buff, 0, contentLen);
uploadSize += contentLen;
};
strm.Close();
// necessary - the upload occurs really here !
response = (FtpWebResponse) request.GetResponse();
// check the response codes... for example FileActionOK...
if ( response.StatusCode == System.Net.FtpStatusCode.FileActionOK )
DoneOK = true;
response.Close(); response = null;
request = null;
}
}
catch
{
};
if ( request != null )
{
if ( response != null )
{
try { response.Close(); } catch {};
response = null;
}
if ( !DoneOK )
{
try { request.Abort (); } catch {};
}
request = null;
}
This was problem related to the FTP Server we were using, when we switched FTP server to IIS then everything worked smoothly.
Thanks for all the help

Categories

Resources