Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have 2 servers, there is no connection between them, one (A) has data input forms and I have to move this data to the second Server (B).

I am sending data from (A) as csv file to the handler in server(b). I used the following code to send data, but file is not receiving at the handler. context.Request.Files.Count is always < 0. (Hanldler is working fine, i have checked the same with a file uploader). what would be wrong in the below code? or any other suggestion to transfer data?

What I have tried:

C#
const string FILE_PATH = "C:\\Docs\\SampleCV.csv";
    const string FILE_NAME = "SampleCV";
    string UPLOADER_URI = string.Format("http://GIC1493-DSK1:82/ExportData.ashx?FILE_NAME={0}", FILE_NAME);
    var httpRequest = WebRequest.Create(UPLOADER_URI) as HttpWebRequest;
    using (Stream stream = File.OpenRead(FILE_PATH))
    {
        httpRequest.Method = "POST";

        //stream.Seek(0, SeekOrigin.Begin);
        //stream.CopyTo(httpRequest.GetRequestStream());
        //var httpResponse = httpRequest.GetResponse();
        //StreamReader reader = new StreamReader(httpResponse.GetResponseStream());
        //var responseString = reader.ReadToEnd();
        //lblMsg.Text = "Posted to server";            

        Stream webStream = null;
        try
        {
            if (stream != null && stream.Length > 0)
            {
                long length = stream.Length;
                httpRequest.ContentLength = length;
                webStream = httpRequest.GetRequestStream();
                stream.CopyTo(webStream);
            }
        }
        finally
        {
            if (null != webStream)
            {
                stream.Flush();
                stream.Close();
                webStream.Flush();
                webStream.Close();
            }
        }
        using (HttpWebResponse response = HttpWebResponse)httpRequest.GetResponse())
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            var responseString = reader.ReadToEnd();
            lblMsg.Text = "Posted to server. Response is : " + responseString; ;
        }
Posted
Updated 16-Mar-17 14:46pm
v2

1 solution

Your handler is expecting a multipart/formdata[^] request, but your code is simply sending the raw bytes of the file.

You need to build a proper request to transmit the file:
C#
public static class Extensions
{
    public static void PrepareFileUpload(this WebRequest request, string fieldName, Stream fileStream, string fileName, string contentType)
    {
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        request.Method = "POST";
        
        using (var stream = request.GetRequestStream())
        using (var writer = new StreamWriter(stream, System.Text.Encoding.ASCII))
        {
            writer.WriteLine();
            writer.WriteLine("--{0}", boundary);
            writer.WriteLine("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", fieldName, fileName);
            writer.WriteLine("Content-Type: {0}", contentType);
            writer.WriteLine();
            writer.Flush();
            
            fileStream.CopyTo(stream);
            
            writer.WriteLine();
            writer.WriteLine("--{0}--", boundary);
        }
    }
}

...

var httpRequest = WebRequest.Create(UPLOADER_URI);
httpRequest.PrepareFileUpload("fieldName", stream, "MyFile.csv", "text/csv");

using (var response = httpRequest.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
    var responseString = reader.ReadToEnd();
    lblMsg.Text = "Posted to server. Response is : " + responseString;
} 


Alternatively, if you're always uploading a file stored on server A's file system, you can use the WebClient class[^]:
C#
using (var client = new WebClient())
{
    byte[] response = client.UploadFile(UPLOADER_URI, FILE_PATH);
    string responseString = Encoding.UTF8.GetString(response);
    lblMsg.Text = "Posted to server. Response is : " + responseString;
}


Or, if you're using .NET 4.0 or higher, you can use the HttpClient class[^]:
C#
private static readonly HttpClient Client = new HttpClient();
...
using (var content = new MultipartFormDataContent())
{
    content.Add(new StreamContent(stream), "fieldName", "MyFile.csv");
    
    using (var response = await Client.PostAsync(UPLOADER_URI, content))
    {
        response.EnsureSuccessStatusCode();
        string responseString = await response.Content.ReadAsStringAsync();
        lblMsg.Text = "Posted to server. Response is : " + responseString;
    }
}

NB: You'll need to make your code async to use this.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900