Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello!

I would like to send files over the local network to an another Computer. On the destination computer, there is a ftp Server running.
Manual connecting to the ftp server from my pc works fine.

So i tried to transfer the files with the FtpWebRequest library, but i always get the error message: "The requested FTP command Is not supported when using HTTP Proxy".
I found some links via google, but whatever i do, it dont work.

Here the methods for sending the file:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(HostAddy);
request.Proxy = null;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("ftp://192.168.0.1","pass");
WebResponse response = request.GetResponse();

FileStream fs = new FileStream("test.txt", FileMode.Open);
byte[] fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, Convert.ToInt32(fs.Length));
fs.Flush();
fs.Close();

Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
request.Abort(); 

So thanks for your help!
Posted
Updated 10-Aug-10 21:56pm
v2

That's right, your code should not work.
Two things you need to take into account:

1) Pay attention: the form of NetworkCredential constructor you're trying to use expect username and password, (not URL and password); you can use username = string.Empty.

2) Another possibility might be using URL in the form "ftp://username:password@192.168.0.1";

3) Your server may require no password; in reality, it can be either empty string or just any character except schema or URL delimiters.

I think this should resolve your problem. If it does not (yet), you need to provide full dump exception information; one important item is the string System.Exception.Stack.

For such dump you can use my codelet I proposed for different Answer, here.
 
Share this answer
 
v4
Or, I can see one more problem. You're just writing some data in output stream which happen to be FTP stream. In what file? Where is your FTP command?!

You're trying to work with FTP protocol as it was plain TCP. Oh!
So what to do? Look at the sample showing how to upload the file:

C#
using System;
using System.Net;
using System.Threading;

using System.IO;
namespace Examples.System.Net
{
    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 (args[0]);
            string 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 does not have to be specified. 
            // The example specifies the credential only to
            // control how actions are logged on the server.

            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

            // 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();
            }
        }
    }
}


Come on! You could not file proper codelet?! The above file upload sample is from Microsoft help (4.0), ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_system.net/html/9a8d5570-4510-75e2-0a39-cefd68f459a9.htm; you'll find other samples on the same page.
 
Share this answer
 
v2
Comments
Espen Harlinn 26-Feb-11 10:49am    
Amazing effort - my 5
Sergey Alexandrovich Kryukov 26-Feb-11 21:52pm    
Thank you for good words, Espen, but...
Actually, is a copy of a sample from Microsoft help on FTP upload. At that time, I though if OP failed to find in regular help, finding it using ms-help:// reference also could be a problem :-)
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900