开发者

Uploading a file: Unable to write data to the transport connection

开发者 https://www.devze.com 2023-03-26 02:54 出处:网络
I am using the following code to upload a file to a CE webserver (IIS).The server code is 100% robust. It intermittently works on some machines or some target WinCE boxes.When it fails it throws the f

I am using the following code to upload a file to a CE webserver (IIS). The server code is 100% robust. It intermittently works on some machines or some target WinCE boxes. When it fails it throws the following error message instantly. Any advice would be great thanks!

Error

{System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size) --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size) at System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state) at System.Net.ConnectStream.Write(Byte[] buffer, Int32 offset, Int32 size) at MUSU.HTTPExtensions.UploadFileEx(String uploadfile, String url, String fileFormName, String contenttype, NameValueCollection querystring, NetworkCredential credentials)

Code

public static void UploadFileEx(String uploadfile, String url,
                    String fileFormName, String contenttype, NameValueCollection querystring,
                    NetworkCredential credentials)
{
    if (String.IsNullOrEmpty(fileFormName))
        fileFormName = "file";

    if (String.IsNullOrEmpty(contenttype))
        contenttype = "applicat开发者_StackOverflowion/octet-stream";

    String postdata = "";

    if (querystring != null)
    {
        if (url.Contains("?")) { postdata = "&"; }
        else { postdata = "?"; }

        foreach (String key in querystring.Keys)
        {
            postdata += key + "=" + querystring.Get(key) + "&";
        }
    }
    Uri uri = new Uri(url + postdata);

    String boundary = "----------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
    if (credentials != null)
        webrequest.Credentials = credentials;
    webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
    webrequest.Method = "POST";
    webrequest.ProtocolVersion = HttpVersion.Version10;
    //webrequest.KeepAlive = false;

    /// Build up the post message header

    StringBuilder sb = new StringBuilder();
    sb.Append("--");
    sb.Append(boundary);
    sb.Append("\r\n");
    sb.Append("Content-Disposition: form-data; name=\"");
    sb.Append(fileFormName);
    sb.Append("\"; filename=\"");
    sb.Append(Path.GetFileName(uploadfile));
    sb.Append("\"");
    sb.Append("\r\n");
    sb.Append("Content-Type: ");
    sb.Append(contenttype);
    sb.Append("\r\n");
    sb.Append("\r\n");

    String postHeader = sb.ToString();
    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

    // Build the trailing boundary string as a byte array

    // ensuring the boundary appears on a line by itself

    byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    using (FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read))
    {
        long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
        webrequest.ContentLength = length;

        using (Stream requestStream = webrequest.GetRequestStream())
        {
            // Write out our post header
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            // Write out the file contents
            byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                requestStream.Write(buffer, 0, bytesRead);

            /// Write out the trailing boundary
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            WebResponse response = webrequest.GetResponse();
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消