简体   繁体   English

修复 - System.Net.WebException:远程服务器返回错误:(500) 语法错误,命令无法识别

[英]Fixing - System.Net.WebException: The remote server returned an error: (500) Syntax error, command unrecognized

I created FTP code to transfer files.我创建了 FTP 代码来传输文件。 This code works fine except that it sometimes causes an error 500. The exact error is -此代码工作正常,但有时会导致错误 500。确切的错误是 -

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.我注意到当加载最大的文件时会发生错误,即大约 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

On reading your question I was suspicious this has to do with (or could be corrected by) setting the KeepAlive to false .在阅读您的问题时,我怀疑这与(或可以通过)将KeepAlive设置为false Looking on SO - this question references the same problem and points to it as well: https://stackoverflow.com/a/2071374/1803682看着 SO - 这个问题引用了同样的问题并指向它: https : //stackoverflow.com/a/2071374/1803682

Try setting:尝试设置:

request.KeepAlive = false;

With KeepAlive set to false your connection will be closed at the end of each request .如果KeepAlive设置为false您的连接将在每个请求结束时关闭 If you are transmitting a lot of files this could be an issue - as it takes time to resend credentials, etc. The upside is you recreate the connection in a known / initial state which should solve your problem (even if it is not the root cause).如果您正在传输大量文件,这可能是一个问题 - 因为重新发送凭据等需要时间。好处是您以已知/初始状态重新创建连接,这应该可以解决您的问题(即使它不是根原因)。

To see what is going on, if you can enable detailed logging on your server you should see the last command issued before seeing this error returned.要查看发生了什么,如果您可以在您的服务器上启用详细日志记录,您应该看到在返回此错误之前发出的最后一条命令。 This should give you a better idea of what is up.这应该让您更好地了解发生了什么。 Found this thread saying much the same thing.发现这个帖子说的差不多。

Update:更新:

If I had read to the bottom of the link I posted myself I could have answered even better, the command probably being reissued is some part of the login process (ie USER username ) and this is your likely issue:如果我阅读了我自己发布的链接的底部,我可以回答得更好,重新发出的命令可能是登录过程的一部分(即USER username ),这可能是您的问题:

The reason the creadentials may no longer be valid is that the WebRequest uses a lease that expires after a certain amount of time.凭据可能不再有效的原因是 WebRequest 使用了在一定时间后到期的租用。 If you don't explicitly instantiate the lease and define its timeouts, the FtpWebRequest appears to use default timeout values.如果您没有显式实例化租约并定义其超时,则 FtpWebRequest 似乎使用默认超时值。 I believe what's happening is that when the lease expires the FtpWebRequest will then try to log on again.我相信发生的事情是当租约到期时 FtpWebRequest 将尝试再次登录。

So looking here with the right search:所以在这里寻找正确的搜索:

yields that the default timeout waiting for requests is not infinite as specified but actually 10000 ms .产生等待请求的默认超时不是指定的无限,而是实际上10000 ms Which seems a pretty big discrepancy.这似乎是一个相当大的差异。 So you can also try setting:所以你也可以尝试设置:

request.Timeout = -1;

And see if it corrects your error.看看它是否纠正了你的错误。


Really don't think this could be your issue so moving it to the bottom:真的不认为这可能是你的问题,所以把它移到底部:

Also - check that your request.ReadWriteTimeout is appropriate for the speed you see for the larger file. 另外 - 检查您的 request.ReadWriteTimeout是否适合您看到的较大文件的速度。 The default is 5 minutes which would be pretty long for 290k, so I expect this is not the source of your error. 默认值是 5 分钟,这对于 290k 来说已经很长了,所以我希望这不是您错误的根源。 Also - I would expect a connection closed error if this was the problem. 另外 - 如果这是问题,我希望连接关闭错误。

I too encountered the same exception with FTPWebRequest within a custom MSBuild task... luckily the task exposed a setting UsePassive="false" (which sets the UsePassive property on the FTPWebRequest object).我在自定义 MSBuild 任务中也遇到了与FTPWebRequest相同的异常......幸运的是,该任务公开了一个设置UsePassive="false" (它在FTPWebRequest对象上设置UsePassive属性)。 Changing the value to "true" fixed the problem.将值更改为"true"解决了问题。 Hope this helps!希望这可以帮助!

  • (Set UsePassive to) false if the client application's data transfer process listens for a connection on the data port; (Set UsePassive to) false如果客户端应用程序的数据传输进程监听数据端口上的连接; otherwise, true if the client should initiate a connection on the data port.否则,如果客户端应在数据端口上发起连接,则为true The default value is true.默认值为true.
  • Setting the UsePassive property to true sends the "PASV" command to the server.UsePassive属性设置为true会将"PASV"命令发送到服务器。 This command requests the server to listen on a data port and to wait for a connection rather than initiate one upon receipt of a transfer command.此命令请求服务器侦听数据端口并等待连接,而不是在收到传输命令后启动连接。
  • If UsePassive is set to true, the FTP server may not send the size of the file, and download progress can always be zero.如果UsePassive设置为 true,则 FTP 服务器可能不会发送文件的大小,并且下载进度可以始终为零。 If UsePassive is set to false , a firewall can raise an alert and block the file download.如果UsePassive设置为false ,防火墙可以发出警报并阻止文件下载。

For any one else that has this issue and the above does not seem to work, I found that when I hit the above error, it was to do with my Username or password.对于遇到此问题并且上述方法似乎不起作用的任何其他人,我发现当我遇到上述错误时,与我的用户名或密码有关。 I am sure there are quite a few people who copy and paste from Excel into SQL, so because of this, SQL picked up that my username/password had a carriage return line feed(When you push enter).我相信有很多人会从 Excel 复制并粘贴到 SQL 中,因此,SQL 发现我的用户名/密码有一个回车换行符(当您按下 Enter 键时)。

My code actually picked up the username as "Myusername & vbcrlf".我的代码实际上选择了用户名作为“Myusername & vbcrlf”。

Hope this helps someone, if they have the same problem.希望这可以帮助某人,如果他们有同样的问题。

Cheers!干杯!

I saw the same behaviour/response from an FTP server and the above answers didn't solve my issue.我从 FTP 服务器看到了相同的行为/响应,上述答案并没有解决我的问题。 Turns out my FTP server required a secure connection.原来我的 FTP 服务器需要安全连接。 Here's the easy fix.这是简单的解决方法。 Enjoy.享受。

request.EnableSsl = true;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.Net.WebException:远程服务器返回错误:(500)内部服务器错误。 - System.Net.WebException: The remote server returned an error: (500) Internal Server Error. System.Net.WebException:远程服务器返回错误:(403)禁止 - System.Net.WebException: The remote server returned an error: (403) Forbidden System.Net.WebException:远程服务器返回错误:(403)禁止 - System.Net.WebException : The remote server returned an error: (403) Forbidden System.Net.WebException:远程服务器返回错误:(401)未经授权。 在System.Net.HttpWebRequest.GetResponse() - System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse() System.Net.WebException-内部服务器错误500 - System.Net.WebException - Internal Server error 500 Jenkins + Sonarqube-未处理的异常:System.Net.WebException:远程服务器返回错误:(401)未经授权 - Jenkins + Sonarqube - Unhandled Exception: System.Net.WebException: The remote server returned an error: (401) Unauthorized System.Net.WebException:远程服务器返回错误:(403)访问Google API时禁止访问 - System.Net.WebException: The remote server returned an error: (403) Forbidden when access Google API System.Net.WebException:远程服务器返回错误:(429)请求太多 - System.Net.WebException: The remote server returned an error: (429) Too Many Requests FtpWebRequest引发System.Net.WebException:远程服务器返回错误:(530)未登录 - FtpWebRequest throws System.Net.WebException: The remote server returned an error: (530) Not logged in System.Net.WebException:远程服务器返回错误:(415)UNSUPPORTED MEDIA TYPE - System.Net.WebException : The remote server returned an error: (415) UNSUPPORTED MEDIA TYPE
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM