I created FTP code to transfer files. This code works fine except that it sometimes causes an error 500. The exact error is -
Error: System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation.
---> System.Net.WebException: The remote server returned an error:
(500) Syntax error, command unrecognized.
at System.Net.FtpWebRequest.CheckError()
at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
at System.Net.CommandStream.Abort(Exception e)
at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
at System.Net.FtpWebRequest.GetRequestStream()
at ST_772dn22cj49ndfddatee.csproj.ScriptMain.Main()
--- End of inner exception stack trace ---
I noticed that the error occurs when the biggest file is loaded, ie about 290 KB. All other files are less than this and i get no exception for them. I don't know why this happens. Can someone tell me why ?
As an aside, in case you notice some room for improvement in my code or logical error, then please mention that as well. I am not really looking for code reviews, but its welcome.
public void Main()
{
Boolean conditions = true;
if(conditions == true)
{
string fileLocation = "my windows directory";
string fileName = "fileName.extension";
string ftpFolder = @"/ftpFolder/";
Boolean ftpMode = true; //passive or active. True = passive
string ftpPassword = "password";
int ftpPort = 21;// the default
string ftpServerName = "server name";
string ftpUserName = "user name";
//Create an object to communicate with the server.
string ftpRequestString = "ftp://" + ftpServerName + ":"
+ ftpPort + ftpFolder + fileName;
try{
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create(ftpRequestString);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
//Set mode
if(ftpMode == true){
request.UsePassive = true;
}
//Copy the file to the request.
string filePath = @fileLocation + "\\" + fileName;
StreamReader sourceStream = new StreamReader(filePath);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
}//try-catch
}
}//main