C# .NET - FTP URI Invalid;

Asked By Martin Nelson
15-Feb-06 01:18 PM
//I am trying to modify a micrsoft example of an ftp client using .net 2.0 framework. This is a console application. I get an uri is invalid for this {"The requested URI is invalid for this FTP command."} could some please look at the code and tell me where I am going wrong?


using System;
using System.Net;
using System.Threading;

using System.IO;
namespace DBDO
{
    public class FtpState
    {
        private ManualResetEvent wait;
        private FtpWebRequest request;
        private string fileName;
        private Exception operationException = null;
        string status;

        public FtpState()
        {
            wait = new ManualResetEvent(false);
        }

        public ManualResetEvent OperationComplete
        {
            get { return wait; }
        }

        public FtpWebRequest Request
        {
            get { return request; }
            set { request = value; }
        }

        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }
        public Exception OperationException
        {
            get { return operationException; }
            set { operationException = value; }
        }
        public string StatusDescription
        {
            get { return status; }
            set { status = value; }
        }
    }
    public class AsynchronousFtpUpLoader
    {
        // Command line arguments are two strings:
        // 1. The url that is the name of the file being uploaded to the server.
        // 2. The name of the file on the local machine.
        //
        public static void Main(string[] args)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;

            Uri target = new Uri("ftp://ftp.placer.dyndns.org/");//args[0]);
            string fileName = "C:\\temp\\test.css";//args[1];
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;

         
          
            /            // Attempting to log in using credentials
            request.Credentials = new NetworkCredential("test", "test");

            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;

            // Get the event to wait on.
            waitObject = state.OperationComplete;

            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback(EndGetStreamCallback),
                state
                );

            // Block the current thread until all operations are complete.
            waitObject.WaitOne();

            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Console.WriteLine("The operation completed - {0}", state.StatusDescription);
            }
        }
        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState)ar.AsyncState;

            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                Console.WriteLine("Writing {0} bytes to the stream.", count);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback(EndGetResponseCallback),
                    state
                    );
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Could not get the request stream.");
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }

        }

        // The EndGetResponseCallback method  
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState)ar.AsyncState;
            FtpWebResponse response = null;
            try
            {
                response = (FtpWebResponse)state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that 
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Error getting response.");
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
    }
}

I assume that the booboo is occurring because of  I assume that the booboo is occurring because of

15-Feb-06 02:21 PM
this line:

request.Method = WebRequestMethods.Ftp.UploadFile; 

You could try creating a custom method for the FTP command STOR instead. Otherwise, have no idea why is happening.

I use enterprisedt FTP for all my FTP stuff, it's open source and a lot more flexible than the new .NET 2.0 stuff.

Hope that helps.

try creating a custom method for  FTP cmd STOR  try creating a custom method for FTP cmd STOR

15-Feb-06 02:30 PM
could you give me an example of what this would look like?

URI is not the same as URL  URI is not the same as URL

13-Jul-06 10:57 AM
In the Async upload method of MSDN FTPWebrequest Sample the URI is the full path to the file you are uploading.  This includes the file name.  In this way you can move and rename a file at the same time.  The sample code is not intuitive that there is no filename to move to and to use the original file name.

So...
[CODE]Uri target = new Uri("ftp://ftp.placer.dyndns.org/");
string fileName = "C:\\temp\\test.css";[/CODE]

needs to be replaced with

[CODE]Uri target = new Uri("ftp://ftp.placer.dyndns.org/test.css");
string fileName = "C:\\temp\\test.css";[/CODE]

This will upload 'C:\Temp\test.css' to 'ftp.placer.dyndns.org/test.css'

The fileName string path is just where to get the file to transfer, the URI is the path to transfer to.
misplaced args  misplaced args
15-Mar-07 04:22 PM

It appears that you have misplaced the text "//args[0]);" after the line

Uri target = new Uri(”ftp://ftp.placer.dyndns.org/”);

Let me know if you get this working, as I'd like to do the same thing.

Create New Account
help
As FtpState = New FtpState() Dim request As FtpWebRequest = CType(WebRequest.Create(target), FtpWebRequest) request.Method = WebRequestMethods.Ftp.UploadFile request.Credentials = New NetworkCredential(args(2), args(3)) state.Request1 = request state.FileName1 = fileName waitObject = state.OperationComplete request.BeginGetRequestStream(New AsyncCallback(AddressOf EndGetStreamCallback), state) waitObject.WaitOne() If Not state.OperationException1 Is Nothing Then Throw As FtpState = CType(ar.AsyncState, FtpState) Dim requestStream As Stream = Nothing Try requestStream = state.Request1.EndGetRequestStream(ar) Dim bufferLength As Integer = 2048 Dim buffer() As Byte = New Byte(bufferLength) {} Dim count As FtpState = New FtpState() Dim request As FtpWebRequest = CType(WebRequest.Create(target), FtpWebRequest) request.Method = WebRequestMethods.Ftp.UploadFile request.Credentials = New NetworkCredential(args(2), args(3)) state.Request1 = request state.FileName1 = fileName waitObject = state.OperationComplete request.BeginGetRequestStream(New AsyncCallback(AddressOf EndGetStreamCallback), state) waitObject.WaitOne() If Not state.OperationException1 Is Nothing Then Throw As FtpState = CType(ar.AsyncState, FtpState) Dim requestStream As Stream = Nothing Try requestStream = state.Request1.EndGetRequestStream(ar) Dim bufferLength As Integer = 2048 Dim buffer() As Byte = New Byte(bufferLength) {} Dim count As FtpState = New FtpState() Dim request As FtpWebRequest = CType(WebRequest.Create(target), FtpWebRequest) request.Method = WebRequestMethods.Ftp.UploadFile request.Credentials = New NetworkCredential(args(2), args(3)) state.Request1 = request state.FileName1 = fileName waitObject = state.OperationComplete request.BeginGetRequestStream(New AsyncCallback(AddressOf EndGetStreamCallback), state) waitObject.WaitOne() If Not state.OperationException1 Is Nothing Then Throw
WebRequest.Create( "ftp: / / " + FTP + " / " + splitfile) 'Call A FileUpload Method of FTP Request Object reqObj.Method = WebRequestMethods.Ftp.UploadFile 'If you want to access Resourse Protected You need to give User Name fileName = args[1]; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; / / This example uses anonymous logon. / / The request is anonymous by default; the credential to wait on. waitObject = state.OperationComplete; / / Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback (EndGetStreamCallback), state ); / / Block the current thread until all operations are complete. waitObject.WaitOne requestStream = null ; / / End the asynchronous call to get the request stream. try { requestStream = state.Request.EndGetRequestStream(ar); / / Copy the file contents to the request stream. const int bufferLength = 2048; byte [] buffer
fileName = args[1]; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; / / This example uses anonymous logon. / / The request is anonymous by default; the credential to wait on. waitObject = state.OperationComplete; / / Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback (EndGetStreamCallback), state ); / / Block the current thread until all operations are complete. waitObject.WaitOne requestStream = null ; / / End the asynchronous call to get the request stream. try { requestStream = state.Request.EndGetRequestStream(ar); / / Copy the file contents to the request stream. const int bufferLength = 2048; byte[] buffer System. Net . FtpWebRequest ) • clsRequest. Credentials = New System. Net . NetworkCredential ( FtpUser, FtpPassword ) • • clsRequest. Method = System. Net . WebRequestMethods . Ftp . UploadFile • • Dim bFile ( ) As Byte = System. IO . File . ReadAllBytes ( filepath & " \ " & filename ) • • • Dim clsStream As