Mse*_*Ali 13 .net c# ftp webclient
我想从FTP服务器读取文件而不将其下载到本地文件.我写了一个函数,但它不起作用:
private string GetServerVersion()
{
WebClient request = new WebClient();
string url = FtpPath + FileName;
string version = "";
request.Credentials = new NetworkCredential(ftp_user, ftp_pas);
try
{
byte[] newFileData = request.DownloadData(new Uri(FtpPath)+FileName);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
}
catch (WebException e)
{
}
return version;
}
Run Code Online (Sandbox Code Playgroud)
Kev*_*Kev 26
这是一个简单的工作示例,使用您的代码从Microsoft公共FTP服务器获取文件:
WebClient request = new WebClient();
string url = "ftp://ftp.microsoft.com/developr/fortran/" +"README.TXT";
request.Credentials = new NetworkCredential("anonymous", "anonymous@example.com");
try
{
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
// Do something such as log error, but this is based on OP's original code
// so for now we do nothing.
}
Run Code Online (Sandbox Code Playgroud)
我想你在代码中错过了这一行的斜杠:
string url = FtpPath + FileName;
Run Code Online (Sandbox Code Playgroud)
也许在FtpPath
和之间FileName
?
Mar*_*ryl 15
如果文件很小,最简单的方法是使用WebClient.DownloadData
:
WebClient client = new WebClient();
string url = "ftp://ftp.example.com/remote/path/file.zip";
client.Credentials = new NetworkCredential("username", "password");
byte[] contents = client.DownloadData(url);
Run Code Online (Sandbox Code Playgroud)
如果小文件是文本文件,请使用WebClient.DownloadString
:
string contents = client.DownloadString(url);
Run Code Online (Sandbox Code Playgroud)
它假定文件内容采用UTF-8编码(普通的ASCII文件也是如此).如果需要使用其他编码,请使用WebClient.Encoding
property.
如果文件很大,那么您需要以块的形式处理它,而不是将其加载到整个内存中,使用FtpWebRequest
:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream stream = request.GetResponse().GetResponseStream())
{
byte[] buffer = new byte[10240];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// process the chunk in "buffer"
}
}
Run Code Online (Sandbox Code Playgroud)
如果大文件是文本文件,并且您希望按行处理它,而不是按固定大小的块处理它,请使用StreamReader
:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.txt");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream stream = request.GetResponse().GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// process the line
Console.WriteLine(line);
}
}
Run Code Online (Sandbox Code Playgroud)
同样,这假定UTF-8编码.如果要使用其他编码,请使用也需要的StreamReader
构造函数重载Encoding
.
归档时间: |
|
查看次数: |
58997 次 |
最近记录: |