Kyver
Kyver

Reputation: 37

Compact Framework - Upload file via REST

I am looking for the best way to transfer files from the compact framework to a server via REST. I have a web service I created using .net Web API. I've looked at several SO questions and other sites that dealt with sending files, but none of them seem to work the for what I need.

I am trying to send media files from WM 6 and 6.5 devices to my REST service. While most of the files are less than 300k, an odd few may be 2-10 or so megabytes. Does anyone have some snippets I could use to make this work?

Thanks!

Upvotes: 0

Views: 709

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

I think this is the minimum for sending a file:

using (var fileStream = File.Open(@"\file.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.destination.com/path");
    request.Method = "POST"; // or PUT, depending on what the server expects
    request.ContentLength = fileStream.Length; // see the note below
    using (var requestStream = request.GetRequestStream())
    {
        int bytes;
        byte[] buffer = new byte[1024]; // any reasonable buffer size will do
        while ((bytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            requestStream.Write(buffer, 0, bytes);
        }
    }

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

        }
    }
    catch (WebException ex)
    {
        // failure
    }
}

Note: HTTP needs a way to know when you're "done" sending data. There are three ways to achieve this:

  • Set request.ContentLength as used in the example, because we know the size of the file before sending anything
  • Set request.SendChunked, to send chunks of data including their individual size
  • You could also set request.AllowWriteStreamBuffering to write to an in-memory buffer, but I wouldn't recommend wasting that much memory on the compact framework.

Upvotes: 2

Related Questions