上传文件:无法将数据写入传输连接

时间:2011-08-04 15:35:22

标签: c# .net file-upload upload httpwebrequest

我使用以下代码将文件上传到CE网络服务器(IIS)。服务器代码100%可靠。它间歇性地在一些机器或一些目标WinCE盒子上工作。当它失败时,它会立即抛出以下错误消息。任何建议都会非常感谢!

错误

  

{System.IO.IOException:无法将数据写入传输   连接:远程强制关闭现有连接   主办。 ---> System.Net.Sockets.SocketException:现有连接   被远程主机强行关闭了   System.Net.Sockets.Socket.Send(Byte []缓冲区,Int32偏移量,Int32   size,SocketFlags socketFlags)at   System.Net.Sockets.NetworkStream.Write(Byte []缓冲区,Int32偏移量,   Int32 size)---内部异常堆栈跟踪结束--- at   System.Net.Sockets.NetworkStream.Write(Byte []缓冲区,Int32偏移量,   在System.Net.PooledStream.Write(Byte []缓冲区,Int32中的Int32大小)   offset,Int32 size)at   System.Net.ConnectStream.InternalWrite(布尔异步,字节[]缓冲区,   Int32偏移量,Int32大小,AsyncCallback回调,对象状态)at   System.Net.ConnectStream.Write(Byte []缓冲区,Int32偏移量,Int32   大小)在MUSU.HTTPExtensions.UploadFileEx(String uploadfile,String   url,String fileFormName,String contenttype,NameValueCollection   查询字符串,NetworkCredential凭证)

代码

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 = "application/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 个答案:

没有答案