Voglio caricare il file da un server a un altro server FTP e in seguito è il mio codice per caricare il file, ma sta generando un errore come:
Il server remoto ha restituito un errore: (550) File non disponibile (ad es. File non trovato, nessun accesso).
Questo mio codice:
string CompleteDPath = "ftp URL";
string UName = "UserName";
string PWD = "Password";
WebRequest reqObj = WebRequest.Create(CompleteDPath + FileName);
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
reqObj.Credentials = new NetworkCredential(UName, PWD);
FileStream streamObj = System.IO.File.OpenRead(Server.MapPath(FileName));
byte[] buffer = new byte[streamObj.Length + 1];
streamObj.Read(buffer, 0, buffer.Length);
streamObj.Close();
streamObj = null;
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length);
reqObj = null;
Per favore, dimmi dove sto andando male?
Assicurati che il tuo percorso ftp sia impostato come mostrato di seguito.
string CompleteDPath = "ftp://www.example.com/wwwroot/videos/";
string FileName = "sample.mp4";
WebRequest reqObj = WebRequest.Create(CompleteDPath + FileName);
Il seguente script funziona perfettamente con me per il caricamento di file e video su un altro server tramite ftp.
FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl + "" + username + "_" + filename);
ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary = true;
ftpClient.KeepAlive = true;
System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
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();
FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
value = uploadResponse.StatusDescription;
uploadResponse.Close();
Ecco un codice di esempio per caricare il file sul server FTP
string filename = Server.MapPath("file1.txt");
string ftpServerIP = "ftp.demo.com/";
string ftpUserName = "dummy";
string ftpPassword = "dummy";
FileInfo objFile = new FileInfo(filename);
FtpWebRequest objFTPRequest;
// Create FtpWebRequest object
objFTPRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name));
// Set Credintials
objFTPRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
// By default KeepAlive is true, where the control connection is
// not closed after a command is executed.
objFTPRequest.KeepAlive = false;
// Set the data transfer type.
objFTPRequest.UseBinary = true;
// Set content length
objFTPRequest.ContentLength = objFile.Length;
// Set request method
objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile;
// Set buffer size
int intBufferLength = 16 * 1024;
byte[] objBuffer = new byte[intBufferLength];
// Opens a file to read
FileStream objFileStream = objFile.OpenRead();
try
{
// Get Stream of the file
Stream objStream = objFTPRequest.GetRequestStream();
int len = 0;
while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
{
// Write file Content
objStream.Write(objBuffer, 0, len);
}
objStream.Close();
objFileStream.Close();
}
catch (Exception ex)
{
throw ex;
}
Puoi anche usare il tipo WebClient
di livello superiore per fare cose FTP con un codice molto più pulito:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://ftpserver.com/target.Zip", "STOR", localFilePath);
}
Nel caso in cui tu stia ancora avendo problemi ecco cosa mi ha superato tutto questo . Stavo ottenendo lo stesso errore nonostante il fatto che potessi vedere perfettamente il file nella directory che stavo cercando di caricare - cioè: I stava sovrascrivendo un file.
Il mio URL ftp sembrava:
// ftp://www.mywebsite.com/testingdir/myData.xml
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebsite.com/testingdir/myData.xml"
Quindi, le mie credenziali usano il mio nome utente tester e PW;
request.Credentials = new NetworkCredential ("tester", "testerpw");
Bene, il mio account ftp "tester" è impostato su " ftp://www.mywebsite.com/testingdir " ma quando effettivamente ftp [dico da Explorer] ho appena messo " ftp: // www .mywebsite.com "ed effettua l'accesso con le credenziali del mio tester e viene automaticamente inviato a" testingdir ".
Quindi, per fare in modo che funzioni in C # ho finito con l'url - ftp://www.mywebsite.com/myData.xml Fornite le credenziali dei miei tester e tutto ha funzionato bene.
Assicurati che l'URL che hai passato a WebRequest.Create
abbia questo formato:
ftp://ftp.example.com/remote/path/file.Zip
Ci sono modi più semplici per caricare un file usando .NET framework.
Il modo più semplice per caricare un file su un server FTP utilizzando .NET framework utilizza il metodo WebClient.UploadFile
:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile("ftp://ftp.example.com/remote/path/file.Zip", @"C:\local\path\file.Zip");
Se hai bisogno di un controllo maggiore, che WebClient
non offre (come la crittografia TLS/SSL, la modalità ASCII, la modalità attiva, ecc.), Usa FtpWebRequest
, come fai tu. Ma puoi rendere il codice più semplice ed efficiente usando 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.UploadFile;
using (Stream fileStream = File.OpenRead(@"C:\local\path\file.Zip"))
using (Stream ftpStream = request.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
}
Per ulteriori opzioni, tra cui monitoraggio dei progressi e caricamento dell'intera cartella, vedere:
Carica il file su FTP usando C #
Ecco la soluzione !!!!!!
Per caricare tutti i file dalla directory locale (es: D:\Documents) all'URL FTP (es: ftp:\{indirizzo IP}\{nome dir sub})
public string UploadFile(string FileFromPath, string ToFTPURL, string SubDirectoryName, string FTPLoginID, string
FTPPassword)
{
try
{
string FtpUrl = string.Empty;
FtpUrl = ToFTPURL + "/" + SubDirectoryName; //Complete FTP Url path
string[] files = Directory.GetFiles(FileFromPath, "*.*"); //To get each file name from FileFromPath
foreach (string file in files)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FtpUrl + "/" + Path.GetFileName(file));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(FTPLoginID, FTPPassword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FileStream stream = File.OpenRead(FileFromPath + "\\" + Path.GetFileName(file));
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
return "Success";
}
catch(Exception ex)
{
return "ex";
}
}