Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 667
  • Last Modified:

Post file via C#

I am trying to post an XML file to a remote server.  I am using C#.net and am a beginner so not only would code be helpful, but describing what and why is also helpful.
0
jhoop2002
Asked:
jhoop2002
  • 6
  • 3
  • 3
1 Solution
 
davidwainwrightCommented:
I created the below to test a webservice.
This is a console app which has two mandatory parameters - the URL of the service, and also the name of the file you;re posting; i.e.
xxx.exe http://www.testdomain.com/testservice.asmx test.xml
Your xml file should already contain the soap headers as this won't add them..

Hope it helps,

Dave
0
 
davidwainwrightCommented:
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Web;

namespace SimpleHttpClient
{
    class SimpleHttpClient
    {
        public static void Main(string[] args)
        {
            string gatewayUrl = args[0];
            string inputXmlQueryFilePath = args[1];
            HttpWebResponse resp = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(gatewayUrl);
                Console.WriteLine("Connecting to URL: " + gatewayUrl);
                string inputXml;
                using (StreamReader inputQueryReader = new StreamReader(inputXmlQueryFilePath))
                {
                    inputXml = inputQueryReader.ReadToEnd();
                }
                Console.WriteLine("Input XML:");
                Console.WriteLine(inputXml);
                string postData = inputXml;
                Console.WriteLine("String created");
                byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
                request.Method = "POST";
                request.ContentType = "text/xml";
                request.ContentLength = postDataBytes.Length;
                SoapAction = "urn:callcredit.plc.uk/soap:callmlapi/XMLSearch";
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                requestStream.Close();

                resp = (HttpWebResponse)request.GetResponse();
                Console.WriteLine("Response from Gateway:");
                StreamReader responsereader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                Console.WriteLine(responsereader.ReadToEnd());

                resp.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine("\r\nThe request URI could not be found or was malformed");
            }
            finally
            {
                if (resp != null)
                {
                    resp.Close();
                }
            }
        }
    }
}
0
 
Bob LearnedCommented:
You can use the WebClient to post to a URL:

using System;
using System.Net;

public class WebPost
{

    public void PostFile(string address, string fileName)
    {
        WebClient client = new WebClient();
        client.UploadFile(address, "POST", fileName);
    }

}

Bob
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
davidwainwrightCommented:
Bob
Pretty Nifty; I'd say the points were yours here..

Dave
0
 
jhoop2002Author Commented:
I'll work with that.  I should have also mentioned that is not a web service.  Just plain old post, also writing this for a website if that matters.
0
 
jhoop2002Author Commented:
also, Id prefer not to have to write this document to the hard drive.  I can build the xmldocument in memory and would like to just upload that
0
 
Bob LearnedCommented:
You can also post data with the WebClient:

using System;
using System.Net;

public class WebPost
{

    public void PostFile(string address, string fileName)
    {
        using (WebClient client = new WebClient())
            client.UploadFile(address, "POST", fileName);
    }

    public void PostData(string address, byte[] data)
    {
        using (WebClient client = new WebClient())
            client.UploadData(address, "POST", data);
    }

}

Bob
0
 
jhoop2002Author Commented:
well, i don't know is that would work
-I don't know how to convert a XmlDocument, or XmlWriter into a byte[]
-I need to accept a response from the post

Here is some sample data, this code uploads a file from the server's hard drive, and i don't want to do that.
    private void SendXML(XmlDocument XmlDoc)
    {
        //WebClient client = new WebClient();
        //client.UploadFile("https://ctt.usis-csd.com/default.asp", "POST", XmlDoc);

        string strFile;
        Byte[] postArray;
        Byte[] responseArray;
        HttpWebRequest objRequest;
        string strRequest;
        UTF8Encoding objUTF8Encoding;
        Stream strmRequest;
        HttpWebResponse objResponse;
        StreamReader srResponse;
        string strReturnedResponse;
        TextReader reader;

        try
        {
            // Upload your file and set a string
            reader = File.OpenText("Filepath");
            strFile = reader.ReadLine;

            // Initialize request object
            objRequest = (HttpWebRequest)WebRequest.Create("https://ctt.usis-csd.com/default.asp");
            objRequest.Method = "POST";
            objRequest.Timeout = 50000; // 5 Mins

            // Create a new WebClient instance
            // "POST-STRING"
            postArray = Encoding.UTF8.GetBytes(XmlDoc);

            // Upload Data implicitly sets HTTP POST as the request method
            // Add body to request
            objRequest.ContentLength = postArray.Length;
            strmRequest = objRequest.GetRequestStream();
            strmRequest.Write(postArray, 0, postArray.Length);
            strmRequest.Close();

            // Get Response
            objResponse = objRequest.GetResponse();
            srResponse = new StreamReader(objResponse.GetResponseStream(), Encoding.ASCII);

            // Decode and display the response.
            strReturnedResponse = srResponse.ReadToEnd();
            srResponse.Close();

            Response.Write(strReturnedResponse);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
0
 
Bob LearnedCommented:
Example:

using System.Text;

...

            XmlDocument document = new XmlDocument();
            byte[] data = UTF8Encoding.UTF8.GetBytes(document.DocumentElement.OuterXml);

Bob
0
 
jhoop2002Author Commented:
I'm sorry, Im assuming that snippet converts an xmldocument into a byte[]??

so here is my code now, along with the error I am getting;
    private void SendXML(XmlDocument XmlDoc)
    {
        string strFile;
        Byte[] data;
        Byte[] postArray;
        Byte[] responseArray;
        HttpWebRequest objRequest;
        string strRequest;
        UTF8Encoding objUTF8Encoding;
        Stream strmRequest;
        HttpWebResponse objResponse;
        StreamReader srResponse;
        string strReturnedResponse;
        TextReader reader;

        try
        {
            //// Upload your file and set a string
            //reader = File.OpenText("Filepath");
            //strFile = reader.ReadLine;

            data = UTF8Encoding.UTF8.GetBytes(XmlDoc.DocumentElement.OuterXml);

            // Initialize request object
            objRequest = (HttpWebRequest)WebRequest.Create("https://ctt.usis-csd.com/default.asp");
            objRequest.Method = "POST";
            objRequest.Timeout = 50000; // 5 Mins

            // Create a new WebClient instance
            // "POST-STRING"
            postArray = Encoding.UTF8.GetBytes(data);

            // Upload Data implicitly sets HTTP POST as the request method
            // Add body to request
            objRequest.ContentLength = postArray.Length;
            strmRequest = objRequest.GetRequestStream();
            strmRequest.Write(postArray, 0, postArray.Length);
            strmRequest.Close();

            // Get Response
            objResponse = objRequest.GetResponse();
            srResponse = new StreamReader(objResponse.GetResponseStream(), Encoding.ASCII);

            // Decode and display the response.
            strReturnedResponse = srResponse.ReadToEnd();
            srResponse.Close();

            Response.Write(strReturnedResponse);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1502: The best overloaded method match for 'System.Text.Encoding.GetBytes(char[])' has some invalid arguments

Source Error:

Line 427:            // Create a new WebClient instance
Line 428:            // "POST-STRING"
Line 429:            postArray = Encoding.UTF8.GetBytes(data);
Line 430:
Line 431:            // Upload Data implicitly sets HTTP POST as the request method
 
0
 
jhoop2002Author Commented:
error on line 429
0
 
jhoop2002Author Commented:
got it;
    private void SendXML(XmlDocument XmlDoc)
    {
        string strFile;
        Byte[] data;
        Byte[] postArray;
        Byte[] responseArray;
        HttpWebRequest objRequest;
        string strRequest;
        UTF8Encoding objUTF8Encoding;
        Stream strmRequest;
        HttpWebResponse objResponse;
        StreamReader srResponse;
        string strReturnedResponse;
        TextReader reader;

        try
        {
            //// Upload your file and set a string
            //reader = File.OpenText("Filepath");
            //strFile = reader.ReadLine;

            postArray = UTF8Encoding.UTF8.GetBytes(XmlDoc.DocumentElement.OuterXml);

            // Initialize request object
            objRequest = (HttpWebRequest)WebRequest.Create("https://ctt.usis-csd.com/default.asp");
            objRequest.Method = "POST";
            objRequest.Timeout = 50000; // 5 Mins

            // Create a new WebClient instance
            // "POST-STRING"
            //postArray = Encoding.UTF8.GetBytes(data);

            // Upload Data implicitly sets HTTP POST as the request method
            // Add body to request
            objRequest.ContentLength = postArray.Length;
            strmRequest = objRequest.GetRequestStream();
            strmRequest.Write(postArray, 0, postArray.Length);
            strmRequest.Close();

            // Get Response
            objResponse = (HttpWebResponse)objRequest.GetResponse();
            srResponse = new StreamReader(objResponse.GetResponseStream(), Encoding.ASCII);

            // Decode and display the response.
            strReturnedResponse = srResponse.ReadToEnd();
            srResponse.Close();

            Response.Write(strReturnedResponse);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now