Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Ftp Command Error Handling in .NET?

Posted on 2007-10-09
14
Medium Priority
?
992 Views
Last Modified: 2013-12-17
Hi All,

I have a .bat file that will call a text file with ftp commands. The commands basically uploads files from my local machine to a remote server. I was wondering is there is a way to catch and write errors if something did not process correctly?. How do I go about doing this. Can this be done in the ftp commands or should I write a C# program to handle the error. Please advise. Below is a quick example of what the ftp command looks like in the text file.

open 10.8.2.64
myusername
mypassword
cd uploadfolder
mput *.doc
close
quit
0
Comment
Question by:tinman1412
  • 6
  • 5
  • 2
  • +1
14 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20043101
If you are using the System.Diagnostics.Process class to execute the batch file, you can redirect the StandardOutput and/or the StandardError to get the necessary output.

Bob
0
 

Author Comment

by:tinman1412
ID: 20044987
do you have code examples?
0
 
LVL 64

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 20046256
Hi tinman1412;

If you want to do it all in managed code you can do it like this.

To use this code to test change the string remoteURI with the URL of the FTP site and change the line that starts with NetworkCredential with the correct user id and password.

using System.Net;
using System.IO;

        // String array to hold the full path of each file to be transfered
        // to the FTP site.
        string[] UploadFiles = null;
        // Get the list of files to be transfered and place them in a string array
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Multiselect = true;
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            // get the list of files to be transfered.
            UploadFiles = ofd.FileNames;
        }
        else
        {
            // No files were selected just return
            return;
        }

        // The web site URL
        string remoteURI = "ftp://10.8.2.64/";
        // Load files to this subdirectory
        string placeFileInFolder = "uploadfolder/";
        // Create the FTP client
        WebClient ftpClient = new WebClient();
        // The user name and password are stored here
        NetworkCredential nc = new NetworkCredential("myusername", "mypassword");
        ftpClient.Credentials = nc;
        // used to check if there were any errors in transfering the files
        Exception err = null;

        for (int idx = 0; idx < UploadFiles.Length; idx++)
        {
            // Call the function to transfer the files to the FTP site
            err = xfer(ftpClient, remoteURI + placeFileInFolder, UploadFiles[idx]);
            // Check to see if there were any errors in the transfer
            if (err != null)
            {
                // Write the error somewhere and reset err to null for the next transfer
                Console.WriteLine(err.Message);
                err = null;
            }
        }


        // client is the FTP client, remoteFile is where on the site the file will be
        // stored, localFile is the full path to the file going to be transfered
        // to the FTP site.
        private Exception xfer(WebClient client, string remoteFile, string localFile)
        {
            Exception retErr = null;
            // Get the file name from the local file to name the file on the remote
            string filename = Path.GetFileName(localFile);
            // Add the file name that the file will be called on the FTP site.
            string WebResources = remoteFile + filename;
            try
            {
                // Transfer the file to the FTP site.
                client.UploadFile(WebResources, localFile);
            }
            catch (Exception ex)
            {
                // If any errors occurred report it to the caller.
                retErr = ex;
            }
            return retErr;
        }

Fernando
0
Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

 

Author Comment

by:tinman1412
ID: 20048417
Are there free ftp servers on the web that I can run the code against?.
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 20048609
Sorry I do not know of any you can test the code with. Can you not try the one you are working with 10.8.2.64 ?
0
 

Author Comment

by:tinman1412
ID: 20049662
Is it possible to configure FTP on my local machine and make it work that way? If so, please show me how
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 20050038
If you have a system that supports IIS, "Internet Information Services", and it is installed on your system then yes. You would need to also enable FTP Services.

To see if it is installed go to the Control Panel -> Administrative Tools and see if you have a component called Internet Information Services. If you do open it up and see if it has FTP enabled and its running.

If you do not have it installed go to the Control Panel and double click on Add/Remove Programs. Once there click on Add or Remove Windows Components and see if "Internet Information Services" is a component available to be installed if yes and you wish to install it you will need the original CD's you loaded windows with to get it loaded.

If you have it loaded and configured the FTP URL for your machine will be ftp://localhost if you run an FTP client from the local computer to get access from another system you will need to get the IP address of your computer. To do that open a DOS Command Prompt window and enter the command ipconfig then the return key. The out put of that command will have a line that reads

        IP Address. . . . . . . . . . . . : XXX.XXX.XXX.XXX

the XXX.XXX.XXX.XXX is the IP Address of your machine.  So lets say that the IP Address is 10.0.50.1 then to make the code I posted work you would change

string remoteURI = "ftp://10.8.2.64/";

in the code to

string remoteURI = "ftp://10.0.50.1/";
0
 

Author Comment

by:tinman1412
ID: 20057171
Ok, I currently have a batch file that calls a text file with the ftp commands to put files onto the remote machine via a windows scheduler. My problem is I'm not able to catch the errors if something occurs. Based on your code, are you suggesting that I basically write a Windows service .exe and run it from the scheduler?. This way, I would no longer need  the batch file and the ftp text file with the commands, I would just use .NET managed code and the FTP object in .NET to transfer the files?

Thanks,
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 20057829
That is correct. Then in this section of code:

    if (err != null)
    {
        // Write the error somewhere and reset err to null for the next transfer
        Console.WriteLine(err.Message);
        err = null;
    }

Write to a log file so that any errors can be corrected by some one.
0
 

Author Comment

by:tinman1412
ID: 20062035
I noticed you are using the "WebClient" class. Will this work. Is there not an FTP class in .net 2005 that can be used. Basically, it will be an ftp site with has a specific username/password credential setup. Does the "WebClient" do this as well?
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 20062735
To your question, "Will this work.", Yes it will I have tested the code before posting as is my normal habit.

To your question, "Is there not an FTP class in .net 2005 that can be used.", The WebClient supports the following protocols, http:, https:, ftp:, and file: scheme identifiers. This is the .Net FTP class. The function that is used is determined by the URL that is given to the WebClient.

To your question, "Basically, it will be an ftp site with has a specific username/password credential setup. Does the "WebClient" do this as well?", The FTP methods of WebClient support username/password when it uses the NetworkCredential class as shown below which I have posted in my solution.

    // The user name and password are stored here
    NetworkCredential nc = new NetworkCredential("myusername", "mypassword");

0
 

Expert Comment

by:lanac222
ID: 20640463
FernandoSoto,
I tried your code and I have valid FTP server. I got error 'An exception occurred during a WebClient request.' What that could be?  I may add some points to if needed.

Thanks.

lanac
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 20640951
That would be hard to tell without having the full error message. But this question has been closed and anyone needing help will need to open a new question.

Thank you.
0
 

Expert Comment

by:lanac222
ID: 20641295
FernandoSoto,

Thank you for your response. I created a new question with ID 23077135.

lanac
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This is the first one of a series of articles I’ll be writing to address technical issues that are always referred to as network problems. The network boundaries have changed, therefore having an understanding of how each piece in the network  puzzl…
Viewers will learn how to properly install and use Secure Shell (SSH) to work on projects or homework remotely. Download Secure Shell: Follow basic installation instructions: Open Secure Shell and use "Quick Connect" to enter credentials includi…
After creating this article (http://www.experts-exchange.com/articles/23699/Setup-Mikrotik-routers-with-OSPF.html), I decided to make a video (no audio) to show you how to configure the routers and run some trace routes and pings between the 7 sites…
Suggested Courses

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question