以下是我在c#中连接到Ftp Server的程序。将.txt文件从本地系统上传到ftp服务器我收到错误"远程服务器返回错误:(404)Not Found&# 34 ;.请帮我解决这个错误。
下面是免费的ftp服务器,用于使用用户名和密码上传文件
地点:http://demo.wftpserver.com/ 用户名:demo-user 密码:演示用户
public static void Main(string[] args)
{
Ftp testConnec = new Ftp();
testConnec.CheckFTPConnection("http://demo.wftpserver.com/");
testConnec.uploadFileToFTP(@"C:\TestFtpConnection", "test_new.txt", "upload", "http://demo.wftpserver.com");
}
public class Ftp
{
#region checkFTPConnection
public bool CheckFTPConnection(string URL)
{
// Uri myUri = new Uri("http://demo.wftpserver.com/");
Uri myUri = new Uri(URL);
// WebRequest myRequest = WebRequest.Create(myUri);
//FtpWebRequest myRequest = (FtpWebRequest)WebRequest.Create(myUri);
WebRequest myRequest = WebRequest.Create(myUri);
myRequest.Credentials = new NetworkCredential("demo-admin", "demo-admin");
myRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
try
{
WebResponse myResponse = myRequest.GetResponse();
long i = myResponse.ContentLength;
return true;
myResponse.Close();
}
// catch (Exception ex)
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
return true;
}
else
{
return false;
}
}
}
#endregion
public bool uploadFileToFTP(string LocalFilePath, string FileName, string Directory,string URL)
{
try
{
Uri myUri = new Uri(URL);
WebRequest myRequest = WebRequest.Create(myUri);
WebRequest ftpClient = WebRequest.Create(myUri + Directory + "/" + FileName);
ftpClient.Credentials = new NetworkCredential("demo-admin", "demo-admin");
ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
System.IO.FileInfo fi = new System.IO.FileInfo(LocalFilePath + "/" + FileName);
ftpClient.ContentLength = fi.Length;
byte[] buffer = new byte[4097];
int bytes = 0;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs = fi.OpenRead();
System.IO.Stream rs = ftpClient.GetRequestStream();
while (total_bytes > 0)
{
bytes = fs.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
//fs.Flush();
fs.Close();
rs.Close();
WebResponse uploadResponse = ftpClient.GetResponse();
// string value = uploadResponse.StatusDescription;
uploadResponse.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}