3

so I'm trying to automate some uploading to an ftp, but I cannot get it to work. What I have is (trying to create a folder):

private void button1_Click(object sender, EventArgs e)
{
    FTPUpload(txtIP.Text, txtUName.Text, txtPWord.Text);
}

private void FTPUpload(string ftpAddress, string ftpUName, string ftpPWord)
{
    FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpAddress + "/AUTO_TEST_FOLDER"));
    ftpRequest.Credentials = new NetworkCredential(ftpUName, ftpPWord);
    ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
    WebResponse response = ftpRequest.GetResponse();
    using (var resp = (FtpWebResponse)ftpRequest.GetResponse())
    {
        MessageBox.Show(resp.StatusCode.ToString());
    }

I keep getting WebException was Unhandled "The remote server returned an error: (550) File unavailable (e.g., file not found, no access)." at line WebResponse response = ftpRequest.GetResponse();.

Can someone help me out here?

I've tried a couple of solutions, including the answer at How do I create a directory on ftp server using C#?, but with no success (no success with even copy/pasting that answer and entering my ip/uname/pword).

Community
  • 1
  • 1
Daevin
  • 778
  • 3
  • 14
  • 31

2 Answers2

5

I managed to get it working with:

private void FtpCreateFolder(string ftpAddress, string ftpUName, string ftpPWord)
    {
            WebRequest ftpRequest = WebRequest.Create("ftp://" + ftpAddress + "/AUTO_TEST_FOLDER");
            ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
            ftpRequest.Credentials = new NetworkCredential(ftpUName, ftpPWord);
    }

I guess the problem was using FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(...). Thanks anyway, SO, hope someone else finds this useful!

Daevin
  • 778
  • 3
  • 14
  • 31
  • I got this exception everytime: `Exception thrown: 'System.Net.WebException' in System.dll "EXCEPTION: An exception occurred during a WebClient request."` – Demilitarized Zone Sep 12 '20 at 05:38
  • @DemilitarizedZone is there more information to the exception? I don't really know what that could be (it's also been 6yrs since I did this, so.... lol). Maybe look into using the HttpClient instead? And make sure to check the MS Docs for proper usage. Sorry I can't help much more. – Daevin Oct 02 '20 at 15:36
  • Thank Daevin for the reply. This finally works for me: `FtpWebRequest ftp_web_request; FtpWebResponse ftp_web_response = null; try { ftp_web_request = (FtpWebRequest)WebRequest.Create(sFolderURL); ftp_web_request.Method = WebRequestMethods.Ftp.MakeDirectory; ftp_web_request.Credentials = new NetworkCredential(sUsername, sPassword); ftp_web_response = (FtpWebResponse)ftp_web_request.GetResponse();} catch { }` Sorry for the messed up comment – Demilitarized Zone Nov 23 '20 at 03:09
0

I know this is an old thread, but I thought I would throw in my 2 cents. In the past I had the issue of getting success or fail back from an FTP server and nothing I could find really worked better than what I pulled from a test program I was using to create my actual application. It seems the big problem comes from getting a response on success or fail when trying to create a folder. The other issue comes since there are multiple Exception types. I have got both WebException and Exception at different points so I hence use a general Exception in my code. It is what works for me. The minor change from the OP is the use of (FtpWebRequest)WebRequest over what they had.

    public static bool CreateFolder(string folder)
    {
        bool success = false;

        System.Net.FtpWebRequest ftp_web_request = null;
        System.Net.FtpWebResponse ftp_web_response = null;

        string ftp_path = @"ftp://foo.bar.com/" + folder;

        try
        {
            ftp_web_request = (FtpWebRequest)WebRequest.Create(ftp_path);
            ftp_web_request.Method = WebRequestMethods.Ftp.MakeDirectory;
            ftp_web_request.Credentials = new NetworkCredential("username", "password");

            ftp_web_response = (FtpWebResponse)ftp_web_request.GetResponse();

            string ftp_response = ftp_web_response.StatusDescription;
            string status_code = Convert.ToString(ftp_web_response.StatusCode);

            ftp_web_response.Close();

            success = true;
        }
        catch (Exception Ex)
        {
            string status = Convert.ToString(Ex);

            MessageBox.Show("Failed to create folder." + Environment.NewLine + status); //debug
        }

        return success;
    }

The following is what I use to upload multiple files. I pass in a Dictionary where the key is the name of the file and the value is the path.

    public static bool UploadFile(string folder, Dictionary<string, string> Photo_Paths)
    {
        bool success = false;

        FtpWebRequest ftp_web_request = null;
        FtpWebResponse ftp_web_response = null;

        foreach (KeyValuePair<string, string> item in Photo_Paths)
        {
            string subdomain = ConfigurationManager.AppSettings["subdomain"];
            string ftp_path = @"ftp://foo.bar.com/" + folder + @"/" + item.Key;

            try
            {
                ftp_web_request = (FtpWebRequest)WebRequest.Create(ftp_path);
                ftp_web_request.UseBinary = true;
                ftp_web_request.UsePassive = false;
                ftp_web_request.EnableSsl = false;
                ftp_web_request.Method = WebRequestMethods.Ftp.UploadFile;
                ftp_web_request.Credentials = new NetworkCredential("username", "password");

                try
                {
                    MessageBox.Show(item.Value); //debug

                    byte[] buffer = File.ReadAllBytes(item.Value);

                    using (Stream file_stream = ftp_web_request.GetRequestStream())
                    {
                        file_stream.Write(buffer, 0, buffer.Length);
                    }

                    ftp_web_response = (FtpWebResponse)ftp_web_request.GetResponse();

                    if (ftp_web_response != null)
                    {
                        string ftp_response = ftp_web_response.StatusDescription;
                        string status_code = Convert.ToString(ftp_web_response.StatusCode);

                        MessageBox.Show(ftp_response + Environment.NewLine + status_code); //debug
                    }
                }
                catch (Exception Ex) //(WebException Ex)
                {
                    //string status = ((FtpWebResponse)Ex.Response).StatusDescription;
                    string status = Convert.ToString(Ex);

                    MessageBox.Show("Failed upload a file." + Environment.NewLine + status); //debug
                }

                ftp_web_response.Close();

                success = true;
            }
            catch (Exception Ex)
            {
                //string status = ((FtpWebResponse)Ex.Response).StatusDescription;
                string status = Convert.ToString(Ex);

                if (ftp_web_response != null)
                {
                    string ftp_response = ftp_web_response.StatusDescription;
                    string status_code = Convert.ToString(ftp_web_response.StatusCode);

                    MessageBox.Show(ftp_response + Environment.NewLine + status_code); //debug
                }

                MessageBox.Show("Failed upload a file." + Environment.NewLine + status); //debug
            }
        }

        return success;
    }
David Bentley
  • 824
  • 1
  • 8
  • 27
  • _"I created this function that works perfect"_ - well, that's like your opinion. It doesn't really work perfect. If there is a credential or connection problem, this code swallows the resulting exception, shows a message box stating "Folder Exists" and returns `false`. That's far from perfect. – CodeCaster May 31 '17 at 15:03
  • I pulled this from my test program so there is stuff in there would obviously be removed or changed. I also fixed that messaged as "Folder Exists" was in an older version of the code. Ideally, I would use a WebException and then see what the exact issue is. – David Bentley May 31 '17 at 15:14
  • Yeah so what's the point of this answer? You've wrapped the existing answer in a try-catch block and posted your method to upload some photos from some very application-specific variables? The second code returns false if the first file succeeds but the second doesn't. It loads entire files in memory (even large ones), which does not scale. Library methods shouldn't catch `Exception` and definitely shouldn't show message boxes. – CodeCaster May 31 '17 at 15:16
  • Again, just stuff from my test program that I have pulled and modified for specific use. One thing that has helped me personally is seeing all the different ways people do things. Even if there are only small differences. What does not help is the negativity that you are displaying. You can comment without being rude. – David Bentley May 31 '17 at 15:30
  • It is a choice to be offended by constructive criticism (in other words I fail to see where I'm being rude). I'm simply warning future readers about the problems that this code displays. One of the things you'll have to live with if you put your code out there for the world to see. :) – CodeCaster May 31 '17 at 15:37
  • Your first comment was fine, I know I need to be better before I copy and paste stuff from my personal library, but the second comment was both bad and good. It is fine to give constructive criticism as it makes me better. But there is also an element of grace that should be used if you are going to be a person that gives feedback to people as they are more receptive if you are not rude. My first gut reaction was to rudeness and not to the actual suggestion for my code. Also, people should not just be copying and pasting this stuff without understanding it anyways. – David Bentley May 31 '17 at 15:42
  • Again, being offended is your choice. I didn't try to offend you, I was asking a genuine question. You say this is a perfect function, but you don't explain what it does, how it does that and how it solves the OP's problem. Do note that Stack Overflow is not a code snippet sharing site, but that answers must answer the question. – CodeCaster May 31 '17 at 15:44
  • Being offended is my choice, but being rude and not having tact is your choice. I edited my post to make it more clear what I am explaining and how I am answering the OP and why I did what I did. If you do not like it, tough. – David Bentley May 31 '17 at 16:08