My Blog

Not a fan of writing but why not give it a try

Sending Files From One Asp Application to Another

In this post I’ll explain how you can send files from one ASP application to another. I’ll be using HttpClient class to make it simpler to send requests. This post is split into two sections of:

  • Sending a request with File
  • Receiving a request with File

This is for API calls so I won’t be using HttpPostedFileBase.

Send a POST request with file content


So first thing we need to do is read a file:

1
2
var filename = "file_name.jpg";
var bytes = File.ReadAllBytes("path\to\file\" + filename);

Now we’ll write the file bytes to a stream:

1
2
var stream = new MemoryStream();
stream.Write(bytes, 0, bytes.Length);

At this point we’re ready to create our request and send it. I’ll add the filename to the request headers. You can even add it to the url as a query string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// VERY IMPORTANT to rewind the stream to the beginning
stream.Seek(0, SeekOrigin.Begin)

// Create Stream objects
var client = new HttpClient();
var content = new StreamContent(stream);

// Add headers
content.Headers.Add("Content-Type", "image/jpeg");
content.Headers.Add("File-Name", filename; // Add filename to headers

// Post the request
// _request_uri should be the path your endpoint
var result = client.PostAsync(_requestUri, content).Result;

Receive the POST request with file content


Receiving the request is much easier. All we have to do is read the content of the POST request:

1
2
3
4
5
[HttpPost]
public async Task<HttpResponseMessage> Post()
{
    var data = await Request.Content.ReadAsStreamAsync();
}

Now you can do anything you want with the file stream stored in data. You can get the File-Name as follows:

1
2
3
4
5
6
7
IEnumerable<string> values;
if (!Request.Headers.TryGetValues("File-Name", out values))
{
    // If filename does not exist return error message
    return new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
}
var filename = values.First<string>();

Data cleanup


Remember to cleanup your disposable objects or nest them in using statements:

1
2
3
4
5
6
7
8
using(var stream = new MemoryStream()) {
    // operations
    using(var client = HttpClient()) {
        using(var content = new StreamContent(stream)) {
            // content operations and sending the request
        }
    }
}

Or explicitly dispose them:

1
2
3
client.Dispose();
content.Dispose();
stream.Dispose();