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
相关产品推荐
相关产品推荐

