tags:

views:

231

answers:

3

I am developing a client-server application - the server being an ASP .NET web app.

The client (a desktop app) needs to send data contained in a text file to my asp .net web app. Data would be approximately 100 KB, in multi-line textual form.

What is the best approach to POST this data to the server, given that I need to do it once every 10 minutes or so?

A: 

I'm confused; you say you want it as a POST param, but then you read it from a header...? That would be the Form for typical post fields, or just the request body for raw data...

For sending form fields:

    NameValueCollection fields = new NameValueCollection();
    fields.Add("name1","some text");
    fields.Add("name2","some more text");
    using (var client = new WebClient())
    {
        byte[] resp = client.UploadValues(address, fields);
        // use Encoding to get resp as a string if needed
    }

For sending a raw file (not as a form; just the text itself), use UploadFile; and for headers, use .Headers.Add.

Marc Gravell
A: 

If your webmethod uses HttpContext.Current.Request.Headers["errorLog"] then your client application needs to send this custom http header when performing the request. Please note that http headers are not meant to send large data.

In your client application you could Add a Web Reference to the service and use the generated proxy class to override the GetWebRequest and add your custom http header:

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
    var req = (HttpWebRequest)base.GetWebRequest(uri);
    var value File.ReadAllText("path_to_your_file");
    req.Headers.Add("errorLog", value);
    return (WebRequest)req;
}
Darin Dimitrov
+2  A: 

If the file is small enough that you can easily fit it in memory (which you would want it to be if you're sending it via POST) then you can simply do the following:

string textFileContents = System.IO.File.ReadAllText( @"C:\MyFolder\MyFile.txt" );

HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://www.myserver.com/myurl.aspx" );
request.Method = "POST";

ASCIIEncoding encoding = new ASCIIEncoding();

string postData = "fileContents=" + System.Web.HttpUtility.UrlEncode( textFileContents );

byte[] data = encoding.GetBytes( postData );

request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

Stream dataStream = request.GetRequestStream();

dataStream.Write( data, 0, data.Length );

dataStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// do something with the response if required

As far as reading the text server side you can just use the Page.Request.Form[ "fileContents" ]

Timothy Walters