Upload file on FTP
Asked Answered
T

7

24

I want to upload file from one server to another FTP server and following is my code to upload file but it is throwing an error as:

The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

This my code:

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; 

Can you please tell me where i am going wrong?

Tical answered 14/4, 2012 at 6:49 Comment(1)
Duplicated here with an interesting answer.Paean
H
39

Please make sure your ftp path is set as shown below.

string CompleteDPath = "ftp://www.example.com/wwwroot/videos/";

string FileName = "sample.mp4";

WebRequest reqObj = WebRequest.Create(CompleteDPath + FileName);

The following script work great with me for uploading files and videos to another servier via 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();
Hymie answered 14/4, 2012 at 7:54 Comment(0)
A
14

Here are sample code to upload file on FTP Server

    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;
    }
Ammunition answered 15/5, 2012 at 13:44 Comment(4)
Any ideas how to upload files to ftp server safely? I mean without leaving exposed server password in the code.Percussionist
You can read in your server password from some source outside the code (such as a config file or registry). However, the user ID and password are going to be passed unencrypted by FTP when it signs into the server, so anyone with access to the wire can see it. Making protecting the password useless since it is exposed by using FTP. If you need secured, you need to use Secure FTP, which is an entirely different thing (requiring third party libraries and certificates).Arundel
You can get password from Config file like web.config or app.config or from registry.Ammunition
It will work for the ASP.NET web application which is hosted on the server and file will be taken by the HTML input type=file tagWasherman
S
14

You can also use the higher-level WebClient type to do FTP stuff with much cleaner code:

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    client.UploadFile("ftp://ftpserver.com/target.zip", "STOR", localFilePath);
}
Ship answered 23/9, 2015 at 13:1 Comment(1)
How do I use it into a method owned by a form class? Thanks in advanceCoaptation
A
2

In case you're still having issues here's what got me past all this. I was getting the same error in-spite of the fact that I could perfectly see the file in the directory I was trying to upload - ie: I was overwriting a file.

My ftp url looked like:

// ftp://www.mywebsite.com/testingdir/myData.xml
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebsite.com/testingdir/myData.xml"

So, my credentials use my tester username and PW;

request.Credentials = new NetworkCredential ("tester", "testerpw");

Well, my "tester" ftp account is set to "ftp://www.mywebsite.com/testingdir" but when I actually ftp [say from explorer] I just put in "ftp://www.mywebsite.com" and log in with my tester credentials and automatically get sent to "testingdir".

So, to make this work in C# I wound up using the url - ftp://www.mywebsite.com/myData.xml Provided my tester accounts credentials and everything worked fine.

Albuminoid answered 25/1, 2013 at 22:2 Comment(0)
B
1
  1. Please make sure your URL that you pass to WebRequest.Create has this format:

     ftp://ftp.example.com/remote/path/file.zip
    
  2. There are easier ways to upload a file using .NET framework.

Easiest way

The most trivial way to upload a file to an FTP server using .NET framework is using WebClient.UploadFile method:

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");

Advanced options

If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, transfer resuming, etc), use FtpWebRequest, like you do. But you can make the code way simpler and more efficient by using 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);
}

For even more options, including progress monitoring and uploading whole folder, see:
Upload file to FTP using C#

Bobbinet answered 15/12, 2018 at 11:37 Comment(0)
I
0

Here is the Solution !!!!!!

To Upload all the files from Local directory(ex:D:\Documents) to FTP url (ex: ftp:\{ip address}\{sub dir name})

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";
        }

    }
Ingeingeberg answered 14/12, 2018 at 10:47 Comment(0)
C
-1
    public void UploadImageToftp()

        {

     string server = "ftp://111.61.28.128/Example/"; //server path
     string name = @"E:\Apache\htdocs\visa\image.png"; //image path
      string Imagename= Path.GetFileName(name);

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}{1}", server, Imagename)));
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential("username", "password");
    Stream ftpStream = request.GetRequestStream();
    FileStream fs = File.OpenRead(name);
    byte[] buffer = new byte[1024];
    int byteRead = 0;
    do
    {
        byteRead = fs.Read(buffer, 0, 1024);
        ftpStream.Write(buffer, 0, byteRead);
    }
    while (byteRead != 0);
    fs.Close();
    ftpStream.Close();
    MessageBox.Show("Image Upload successfully!!");
}
Cancroid answered 25/5, 2017 at 5:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.