You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#通过FTP上传XML文件时文件始终为空的问题排查

问题原因及修复方案

你的代码存在两处关键问题,导致上传的文件始终为空:

1. 重复获取请求流引发状态异常

你先调用了ftpStream = ftpRequest.GetRequestStream();获取请求流,但未向该流写入任何数据;随后在内部try块中又再次调用ftpRequest.GetRequestStream()获取新流。虽然你向第二个流写入了数据,但重复获取流会打乱FTP请求的流状态,最终导致数据无法正确提交到服务器。

2. 无效注释存在语法隐患

代码中的/是无效的单行注释写法,应改为//。虽然这不会直接导致文件为空,但可能引发编译错误或其他潜在问题。


修复后的完整代码

{           
    FtpWebRequest ftpRequest = null;
    Stream requestStream = null;           
    string strMsg = string.Empty;
    try
    {
        String uploadUrl = String.Format("{0}/{1}", "ftp://IPADDRESS", "myfile.xml");
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uploadUrl));
       
        ftpRequest.Credentials = new NetworkCredential("username", "password");
        // 修复无效注释
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        ftpRequest.Timeout = 2000000;               
        ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

        // 仅获取一次请求流并写入数据
        byte[] fileContent = System.Text.Encoding.Default.GetBytes(s);
        ftpRequest.ContentLength = fileContent.Length;
        requestStream = ftpRequest.GetRequestStream();
        requestStream.Write(fileContent, 0, fileContent.Length);
        // 刷新流确保所有数据发送完成
        requestStream.Flush();
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
        strMsg = "File Upload Status: " + response.StatusDescription;
        response.Close();
    }
    catch (Exception ex) {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        // 确保资源被正确释放
        requestStream?.Dispose();
        ftpRequest?.Abort();
    }
}

额外优化建议

  • 使用using语句自动管理流生命周期,避免手动关闭遗漏:
    using (Stream requestStream = ftpRequest.GetRequestStream())
    {
        requestStream.Write(fileContent, 0, fileContent.Length);
        requestStream.Flush();
    }
    
  • 避免依赖Encoding.Default(其依赖系统默认编码,易引发字符错误),建议明确指定编码(如Encoding.UTF8)。
  • 获取响应后务必调用response.Close()释放资源,使用response.StatusDescription可获取更准确的上传状态。

内容的提问来源于stack exchange,提问作者Mathlan89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:52:36