user1814595
user1814595

Reputation: 143

Send Files using Httpwebrequest

hi i'm trying to send xml files from a folder using webservice to another folder in my local computer, files are sent successfully and the application is closed normally but the problem is that files takes forever modified in the destination folder and when i try to call the webservice again it gives me exception time out. here is my code

public void SendC_XML(string path, string queueID, string application, string servicewTMURI)
    {


        HttpWebRequest httpWebRequest2 = null;
        //Stream memStream = null;
        //FileStream fileStream = null;

        String[] listOfFiles = Directory.GetFiles(path, "*.xml");






        for (int i = 0; i < listOfFiles.Length; i++)
        {
            try
            {
                MyLog.Add("found path " + listOfFiles[i]);

                string[] ImagesArray = listOfFiles[i].Split('\\');
                string ImageName = ImagesArray[ImagesArray.Length - 1];
                int index = ImageName.IndexOf(".");
                if (index > 0)
                    ImageName = ImageName.Substring(0, index);


                MyLog.Add("image name = " + ImageName);


                string[] textArray1 = new string[] { servicewTMURI, "/Queue/SetFile/", application, "/", queueID, "/" + ImageName + "/xml" };
                string requestUriString = string.Concat(textArray1);

                Guid guid = new Guid();
                string boundary = "---------------------------" + guid;



                httpWebRequest2 = (HttpWebRequest)WebRequest.Create(requestUriString);
                httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
                boundary;
                MyLog.Add("ContentType = " + httpWebRequest2.ContentType);

                httpWebRequest2.Method = "POST";
                httpWebRequest2.KeepAlive = false;
                httpWebRequest2.Timeout = 5000;
                httpWebRequest2.Proxy = null;

                httpWebRequest2.ServicePoint.ConnectionLeaseTimeout = 5000;
                httpWebRequest2.ServicePoint.MaxIdleTime = 5000;

                httpWebRequest2.Credentials =
                System.Net.CredentialCache.DefaultCredentials;


                using (Stream memStream = new System.IO.MemoryStream())
                {


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


                    string formdataTemplate = "\r\n--" + boundary +
                    "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";






                    memStream.Write(boundarybytes, 0, boundarybytes.Length);

                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

                    //for (int i = 0; i < files.Length; i++)
                    //{

                    //MyLog.Add("file = " + files[i]);
                    string header = string.Format(headerTemplate, "uplTheFile", listOfFiles[i]);

                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

                    memStream.Write(headerbytes, 0, headerbytes.Length);

                    using (FileStream fileStream = new FileStream(listOfFiles[i], FileMode.Open, FileAccess.Read))
                    {
                        byte[] buffer = new byte[1024];

                        int bytesRead = 0;

                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            memStream.Write(buffer, 0, bytesRead);

                        }


                        memStream.Write(boundarybytes, 0, boundarybytes.Length);


                        fileStream.Close();
                    }

                    httpWebRequest2.ContentLength = memStream.Length;

                    using (Stream requestStream = httpWebRequest2.GetRequestStream())
                    {
                        memStream.Position = 0;
                        byte[] tempBuffer = new byte[memStream.Length];
                        memStream.Read(tempBuffer, 0, tempBuffer.Length);
                        memStream.Close();



                        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                        requestStream.Close();

                    }
                    //httpWebRequest2.Abort();
                    httpWebRequest2 = null;

                    //webResponse2 = null;

                }


            }
            catch (Exception ex)
            {
                MyLog.Add("error in cXML method = " + ex.Message);
            }
            finally
            {
                //memStream.Close();
                //fileStream.Close();
                //requestStream.Close();

                try
                {
                    if (httpWebRequest2 != null)
                    {
                        MyLog.Add("heeeeeeeeeeeeeeey request != null");
                        httpWebRequest2.GetRequestStream().Close();
                        httpWebRequest2 = null;
                    }

                }
                catch (Exception exception2)
                {
                    throw exception2;
                }

            }




        }

    }

Upvotes: 3

Views: 9778

Answers (1)

Aydin
Aydin

Reputation: 15294

You can use this to upload files using multi-part form data, if this doesn't work, show how you've implemented the service receiving the file

public void Upload(string uri, string filePath)
{   
    string formdataTemplate = "Content-Disposition: form-data; filename=\"{0}\";\r\nContent-Type: image/jpeg\r\n\r\n";
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.ServicePoint.Expect100Continue = false;
    request.Method = "POST";
    request.ContentType = "multipart/form-data; boundary=" + boundary;

    using(FileStream fileStream    = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, Path.GetFileName(filePath));   
            byte[] formbytes = Encoding.UTF8.GetBytes(formitem);
            requestStream.Write(formbytes, 0, formbytes.Length);
            byte[] buffer = new byte[1024 * 4];
            int bytesLeft = 0;

            while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                requestStream.Write(buffer, 0, bytesLeft);
            }

        }
    }

    try
    {           
        using (HttpWebResponse response    = (HttpWebResponse)request.GetResponse()) { }

        Console.WriteLine ("Success");
    }
    catch (Exception ex)
    {
        throw;
    }
}

Upvotes: 3

Related Questions