WebClient throws SocketException (Invalid argument)

Viewed 985

I use the code below in an attempt to create a file to an ftp server. However i get a socket exception. Can anyone help me solve this exception? Same issue seem to happen when I use the UploadFile(uri, filepath) function.

I tried with setting the credentials as NetworkCredentials too in the options of WebClient but getting the same result.

Got the same result on a remote ftp server too.

Im using .NET 4.7.1

byte[] xmlBytes = XmlDocumentToByteArray(xml);

WebClient webclient = new WebClient() {
    Proxy = null
};

Uri uri = new Uri("ftp://test:test@localhost/test.xml");
//Uri uri = new Uri("ftp://localhost/test.xml");
webclient.UploadData(uri, xmlBytes);

Exception: (In english: An invalid argument was supplied)

System.Net.WebException: Er is een ongeldig argument opgegeven ---> System.Net.Sockets.SocketException: Er is een ongeldig argument opgegeven
   bij System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
   bij System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
   bij System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
   bij System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
   bij System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
   bij System.Net.FtpWebRequest.QueueOrCreateConnection()
   bij System.Net.FtpWebRequest.SubmitRequest(Boolean async)
   --- Einde van intern uitzonderingsstackpad ---
   bij System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
   bij System.Net.WebClient.UploadData(Uri address, String method, Byte[] data)
   bij System.Net.WebClient.UploadData(Uri address, Byte[] data)
   bij ProbeOrderPlacement.Order.OrderSubmit.SubmitOrder(XmlDocument xml) in H:\VSWorkspace\VSTS\Quantore\Probe\ProbeOrderPlacement\Order\OrderPlacement.cs:regel 28

Also tried the following code, but it trows the same exception (but on .GetRequestStream())

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://127.0.0.1/test.xml"));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Proxy = null;
request.UseBinary = true;
request.Credentials = new NetworkCredential("test", "test");
request.ContentLength = xmlBytes.Length;

//Upload the data
using(Stream requestStream = request.GetRequestStream()) {
    requestStream.Write(xmlBytes, 0, xmlBytes.Length);
}

Exeption: (In english: An invalid argument was supplied)

System.Net.WebException: Er is een ongeldig argument opgegeven ---> System.Net.Sockets.SocketException: Er is een ongeldig argument opgegeven
   bij System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
   bij System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
   bij System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
   bij System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
   bij System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
   bij System.Net.FtpWebRequest.QueueOrCreateConnection()
   bij System.Net.FtpWebRequest.SubmitRequest(Boolean async)
   --- Einde van intern uitzonderingsstackpad ---
   bij System.Net.FtpWebRequest.GetRequestStream()
   bij ProbeOrderPlacement.Order.OrderSubmit.SubmitOrder(XmlDocument xml)
4 Answers

Based on this comment by Hans Passant

This is a very low-level mishap, nothing to do with the arguments you passed since they don't get used until later. The underlying OS function (WSASocket) failed, seemingly unhappy about creating a TCP socket. That should never happen of course. But crap happens with networking code, there is always far too much junk hanging off a socket that professes to keep your machine safe and running smoothly. Disable the installed anti-malware product first, any kind of firewall and whatnot next.

I figured out that for my case the problem was the fact that I had the repository of my solution on a Network drive my company provides me. My best guess is that the upload failed due to underlying security measures although I didn't dig into it deep enough to be able to prove this was the case.

Creating a new local repository on my c drive overcame the issue.

So advice for feature readers that experience the same thing, would be to look at the underlying infrastructure to overcome the problem.

Look at WebClient.UploadFile Method.Second argument is file name.There is no overload for byte[]

try this

webclient.UploadData(uri, xmlfilename);

Your ftp url seems to be wrong. Change your code to

byte[] xmlBytes = XmlDocumentToByteArray(xml);
WebClient webclient = new WebClient
{
      Proxy = null,
      Credentials = new NetworkCredential("test", "test")
};

Uri uri = new Uri("ftp://localhost/test.xml");
webclient.UploadData(uri, xmlBytes);

I just tried your code as-is except one change (reading XML file and converting it to byte[]) and I was able to upload the file without any problem.

enter image description here

Since you have not shared your XML structure or the method you are using to read and convert XML into byte[], I went with simplest form of XML and the out-of-the-box method in .NET to read and convert the file data into byte[].

Here is the XML text from source.xml file:

<System>
    <E01></E01>
    <E02></E02>
    <E03></E03>
</System>

Here is my code to read-convert-upload source.xml on ftp server:

        byte[] xmlBytes = File.ReadAllBytes ("D:\\source.xml");

        WebClient webclient = new WebClient ()
        {
            Proxy = null
        };

        Uri uri = new Uri ("ftp://ftp_user:ftp_password@localhost/test.xml");
        //Uri uri = new Uri("ftp://localhost/test.xml");
        webclient.UploadData (uri, xmlBytes);

NOTE: This is a Winforms application build on .NET Framework 4.7.1

If you have any specific requirement in terms of XML structure or the way you need to read the file, you can share the same and we can discuss this further.

Alternatively, you can share a trimmed-down version of your solution on Github for others the troubleshoot.

Hope this helps!

Related