我需要使用c#将文本文件从本地机器上传到ftp服务器。 我尝试过以下代码,但确实没有用。
private bool UploadFile(FileInfo fileInfo)
{
FtpWebRequest request = null;
try
{
string ftpPath = "ftp://www.tt.com/" + fileInfo.Name
request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.Credentials = new NetworkCredential("ftptest", "ftptest");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = false;
request.Timeout = 60000; // 1 minute time out
request.ServicePoint.ConnectionLimit = 15;
byte[] buffer = new byte[1024];
using (FileStream fs = new FileStream(fileInfo.FullPath, FileMode.Open))
{
int dataLength = (int)fs.Length;
int bytesRead = 0;
int bytesDownloaded = 0;
using (Stream requestStream = request.GetRequestStream())
{
while (bytesRead < dataLength)
{
bytesDownloaded = fs.Read(buffer, 0, buffer.Length);
bytesRead = bytesRead + bytesDownloaded;
requestStream.Write(buffer, 0, bytesDownloaded);
}
requestStream.Close();
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
request = null;
}
return false;
}// UploadFile
任何建议???
答案 0 :(得分:0)
您需要通过调用GetResponse()
实际发送请求。
您还可以通过调用fs.CopyTo(requestStream)
来简化您的代码。
答案 1 :(得分:0)
我用一点ftp代码修改并得到以下内容,这似乎对我来说非常好。
ftpUploadloc 是ftp://ftp.yourftpsite.com/uploaddir/yourfilename.txt
ftpUsername 和 ftpPassword 应该是不言自明的。
最后 currentLog 是您要上传的文件的位置。
如果其他人有任何其他我欢迎的建议,请告诉我这对您有何影响。
private void ftplogdump()
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUploadloc);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
StreamReader sourceStream = new StreamReader(currentLog);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
// Remove before publishing
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}