我在通过 SSL 将文件上传到 ftp 站点到特定目录时遇到问题。为此,我正在使用 System.Net.FtpWebRequest
class
。上传顺利。但是文件总是掉落到主目录。知道可能做错了什么吗?感谢您的帮助。
public bool UploadFile(string srcFilePath, string destFilePath = null)
{
if (String.IsNullOrWhiteSpace(srcFilePath))
throw new ArgumentNullException("Source FilePath.");
if (String.IsNullOrWhiteSpace(destFilePath))
destFilePath = Path.GetFileName(srcFilePath);
Uri serverUri = GetUri(destFilePath);
//// the serverUri should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
return false;
// get the object used to communicate with the server.
FtpWebRequest request = CreateFtpRequest(serverUri, WebRequestMethods.Ftp.UploadFile);
// read file into byte array
StreamReader sourceStream = new StreamReader(srcFilePath);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
// send bytes to server
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Debug.WriteLine("Response status: {0} - {1}", response.StatusCode, response.StatusDescription);
return true;
}
private FtpWebRequest CreateFtpRequest(Uri serverUri, string method)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.EnableSsl = true;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
request.Credentials = new NetworkCredential(_userName, _password);
request.Method = method;
return request;
}
private Uri GetUri(string remoteFilePath)
{
return new Uri(_baseUri, remoteFilePath);
}
最佳答案
好的。终于想通了。这是.NET 4.0 框架问题。使用 .NET 3.5 构建解决方案,效果非常好。
讨厌看到 Microsoft 新发布的 .NET 中的错误,并且浪费大量时间来找出问题。
关于c# - FTP over SSL 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14715210/