GetRequestStream()抛出异常

时间:2015-12-30 01:52:44

标签: c#

我正在尝试将文本文件上传到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();

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

1 个答案:

答案 0 :(得分:0)

你无法获得失败原因的详细信息。直到或除非您访问StatusDescription属性的值。

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

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

请参阅我的回答以获取更改工作目录方案。您将在此处获得详细说明。 https://stackoverflow.com/a/32724574/4553745