【发布时间】:2013-02-05 19:20:03
【问题描述】:
我在通过 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);
}
【问题讨论】:
-
不显示您的代码,不可能有人可以帮助您。
-
Raj当您在此处调试此行时Uri serverUri = GetUri(destFilePath);serverUri的确切值是多少?? -
ftp 路径解析为正确路径。 IE。 ftp.xxxx.com/ch02/test.xml但是文件被转移到ftp.xxxx.com/text.xml