c#为什么FTP上传有时只能成功?

时间:2016-03-22 15:45:52

标签: c# ftp

我正在开发一个项目,它收集一些.CSV文件的信息,然后将文件发送到ftp服务器。

程序有时会成功发送文件,但有时它会停止并抛出错误:

System.dll

中出现未处理的“System.Net.WebException”类型异常

附加信息:远程服务器返回错误:227进入被动模式(192,168,10,170,216,244)

任何人都可以发现任何事情,我做错了吗?

提前致谢。

这是我的代码

        private void sendFile_Click(object sender, EventArgs e)
    {
        Upload("ftp://100.64.44.12", "UsernameHere", "PasswordHere", @"C:\Users\Kasper\Documents\testFolder\data.csv");
    }

    public void Upload(string FTPAddress, string username, string password, string filePath)
    {
        FileStream stream = File.OpenRead(filePath);
        byte[] buffer = new byte[stream.Length];
        stream.Read(buffer, 0, buffer.Length);
        stream.Close();

        FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" +
        Path.GetFileName(filePath));
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential(username, password);
        request.UsePassive = true;
        request.UseBinary = false;
        request.KeepAlive = true;

        StreamReader sourceStream = new StreamReader("testfile.txt");
        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();

        MessageBox.Show("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
    }

1 个答案:

答案 0 :(得分:-1)

尝试设置FtpWebRequest.UsePassive = false