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?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
R.D.
  • 7,153
  • 7
  • 22
  • 26
  • Duplicated [here](http://stackoverflow.com/q/15268760/1178314) with an interesting [answer](http://stackoverflow.com/a/26365607/1178314). – Frédéric Sep 23 '15 at 11:04

7 Answers7

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();
irfanmcsd
  • 6,533
  • 7
  • 38
  • 53
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;
    }
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Jayesh Sorathia
  • 1,596
  • 15
  • 16
  • Any ideas how to upload files to ftp server safely? I mean without leaving exposed server password in the code. – martynaspikunas Jan 23 '14 at 03:07
  • 2
    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). – StarPilot Jul 01 '14 at 16:43
  • You can get password from Config file like web.config or app.config or from registry. – Jayesh Sorathia Jul 02 '14 at 08:35
  • 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` tag – Kalpesh Rajai Feb 10 '16 at 10:05
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);
}
Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
user1086279
  • 101
  • 1
  • 4
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#

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
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";
        }

    }
-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!!");
}
Soumya
  • 1