【问题标题】:how connect with ftp from code如何通过代码连接 ftp
【发布时间】:2014-12-22 16:18:00
【问题描述】:
您好,如何在此代码中将我们的 ftp 替换为我们在驱动程序地址上的服务器?
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp");
例如:
string[] filePaths = Directory.GetFiles(@"our ftp address", "*.bmp");
第一个代码运行良好,但第二个代码不起作用!?
tnx
【问题讨论】:
标签:
c#
ftp
drive
getfiles
【解决方案1】:
这个简短的程序将使用 ListDirectoryDetails 方法列出来自 FTP 服务器的文件和目录。还有一个 ListDirectory 方法,它只列出名称。
using System;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
WebRequest ftp = FtpWebRequest.Create("ftp://ftp.ed.ac.uk/");
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
using (WebResponse rsp = ftp.GetResponse())
{
using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
}
【解决方案2】:
来自http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx 的示例
DisplayFileFromServer(你的 bmp 文件)
`public static bool DisplayFileFromServer(Uri serverUri)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
try
{
byte [] newFileData = request.DownloadData (serverUri.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
return true;
}`