FtpWebRequest Scarica File
-
03-10-2019 - |
Domanda
Il seguente codice ha lo scopo di recuperare un file tramite FTP. Tuttavia, sto ottenendo un errore con esso.
serverPath = "ftp://x.x.x.x/tmp/myfile.txt";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);
request.KeepAlive = true;
request.UsePassive = true;
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
// Read the file from the server & write to destination
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
using (StreamWriter destination = new StreamWriter(destinationFile))
{
destination.Write(reader.ReadToEnd());
destination.Flush();
}
L'errore è:
Il server remoto ha restituito un errore: (550) File non disponibile (per esempio, file non trovato, nessun accesso)
Il file non sicuramente esiste sulla macchina remota e sono in grado di eseguire questa ftp manualmente (vale a dire non ho i permessi). Qualcuno può dirmi il motivo per cui potrebbe essere sempre questo errore?
Soluzione
Questo paragrafo dalla forza del FptWebRequest di riferimento di classe essere di interesse per voi:
L'URI può essere relativo o assoluto. Se l'URI è della forma " ftp://contoso.com/%2fpath " (% 2f è un sfuggito '/'), poi l'URI è assoluta, e la directory corrente è /sentiero. Se, tuttavia, l'URI è del formare " ftp://contoso.com/path ", prima .NET Framework accede al FTP Server (utilizzando il nome utente e la password impostata dalle credenziali proprietà), quindi la directory corrente è impostato su percorso /.
Altri suggerimenti
So che questo è un vecchio post, ma io sono l'aggiunta per riferimenti futuri. Ecco una soluzione che ho trovato:
private void DownloadFileFTP()
{
string inputfilepath = @"C:\Temp\FileName.exe";
string ftphost = "xxx.xx.x.xxx";
string ftpfilepath = "/Updater/Dir1/FileName.exe";
string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
byte[] fileData = request.DownloadData(ftpfullpath);
using (FileStream file = File.Create(inputfilepath))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
MessageBox.Show("Download Complete");
}
}
aggiornato in base su ottimo suggerimento di Ilya Kogan
Il modo più semplice
Il modo più banale per scaricare un file binario da un server FTP utilizzando il framework .NET utilizza WebClient.DownloadFile
:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
"ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
Opzioni avanzate
FtpWebRequest
, solo se è necessario un controllo maggiore, che WebClient
non offre (come TLS / SSL crittografia , monitorare i progressi, ecc). Un modo semplice è quello di copiare solo un flusso di risposta FTP per FileStream
utilizzando Stream.CopyTo
:
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 ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
ftpStream.CopyTo(fileStream);
}
Progress monitoraggio
Se avete bisogno di controllare un avanzamento del download, è necessario copiare il contenuto da pezzi da soli:
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 ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
byte[] buffer = new byte[10240];
int read;
while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, read);
Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
}
}
Per GUI di avanzamento (WinForms ProgressBar
), vedi:
scaricare FtpWebRequest FTP ProgressBar
Download cartella
Se volete scaricare tutti i file da una cartella remota, vedere
C # scaricare tutti i file e le sottodirectory tramite FTP .
Ho avuto lo stesso problema!
La mia soluzione era quella di inserire la cartella di public_html
nella URL di download.
posizione del file reale sul server:
myhost.com/public_html/myimages/image.png
Web URL:
www.myhost.com/myimages/image.png
private static DataTable ReadFTP_CSV()
{
String ftpserver = "ftp://servername/ImportData/xxxx.csv";
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
// use the stream to read file from FTP
StreamReader sr = new StreamReader(responseStream);
DataTable dt_csvFile = new DataTable();
#region Code
//Add Code Here To Loop txt or CSV file
#endregion
return dt_csvFile;
}
Spero che possa aiutare.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);
Dopo questo si può utilizzare il sotto la linea per evitare di errori .. (accesso negato, ecc.)
request.Proxy = null;
public void download(string remoteFile, string localFile)
{
private string host = "yourhost";
private string user = "username";
private string pass = "passwd";
private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
private int bufferSize = 2048;
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception) { }
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception) { }
return;
}