GetRequestStream()引发异常

本文关键字:异常 GetRequestStream | 更新日期: 2023-09-27 18:28:23

我正在尝试将文本文件上传到FTP服务器。

这是代码:

public void upload(string remoteFile, string localFile)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)WebRequest.Create(" ftp://Gamification.somee.com/test.txt");
        //ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = false;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = false;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
        /* Establish Return Communication with the FTP Server */
        ftpStream = ftpRequest.GetRequestStream();
        /* Open a File Stream to Read the File for Upload */
        FileStream localFileStream = new FileStream(localFile, FileMode.Open);
        /* Buffer for the Downloaded Data */
        byte[] byteBuffer = new byte[bufferSize];
        int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
        /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
        try
        {
            while (bytesSent != 0)
            {
                ftpStream.Write(byteBuffer, 0, bytesSent);
                bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                MessageBox.Show("succeded");
            }
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        localFileStream.Close();
        ftpStream.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

但是函数在运行这行时抛出异常

ftpStream = ftpRequest.GetRequestStream();

我认为URL中有问题,可能与IP有关,但我无法解决。

GetRequestStream()引发异常

您将无法了解其失败的详细原因。直到或除非您访问StatusDescription属性的值。

catch(WebException ex)
{
    string message = ((HttpWebResponse)ex.Response).StatusDescription;
}

让我们知道消息是怎么说的,这样我们就可以尝试解决这个问题。我无法对此发表评论,因此将其添加为答案。

请参考我的答案,了解更改工作目录场景。你会在这里得到详细的解释。https://stackoverflow.com/a/32724574/4553745