我在 IIS 服务器上使用网站面板。 我想使用 ftp 上传文件
我使用了这段代码:
try
{
WebClient webClient = new WebClient();
OpenFileDialog fd = new OpenFileDialog();
fd.ShowDialog();
MessageBox.Show(fd.FileName);
webClient.UploadFileTaskAsync(new Uri("ftp://" + "username" + ":" +"pass" +"@" + "address/" + "name.ext"), fd.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
这段代码运行没有错误。当我使用网站面板的文件管理器时,创建了一个“Name.ext”文件,但该文件大小为 0 KB。为什么?我的问题是什么?!
我确信 Windows 防火墙允许我这样做。
更新:我正在使用 UploadFileTask 和 UploadFile(非异步)进行更新,但结果与异步相同 :(
最佳答案
您的异常可能会被吞没在从 WebClient.UploadFileTaskAsync
返回的未等待任务中。您应该await
执行您的任务,这样您的catch
block 就会检测到潜在的异常,因为它会传播到等待的代码行:
public async Task UploadFileByFtpAsync()
{
try
{
WebClient webClient = new WebClient();
OpenFileDialog fd = new OpenFileDialog();
fd.ShowDialog();
MessageBox.Show(fd.FileName);
Task<byte[]> response = await webClient.UploadFileTaskAsync(new Uri("ftp://" + "username" + ":" +"pass" +"@" + "address/" + "name.ext"), fd.FileName);
// You might want to validate the response status code is valid here
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
// Do useful exception handling here
}
}
编辑
正如我在评论中所说,检查 response
变量,它包含您可能已失败的上传尝试的响应。
编辑2
问题似乎出在 web/ftp 请求的 KeepAlive
属性上。 The underlying connection was closed: The server committed a protocol violation. FTP 中有一个可接受的答案和 here
关于c# - 使用ftp上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24853696/