Skip to content
Nathan Baulch edited this page Jun 16, 2014 · 1 revision

Download

Files can be download as raw binary data or attached to a resource. The following example uses the special file attachment sub-endpoint to download an attachment, output the file's MIME type and write its contents to a temporary file.

var client = new SDataClient("http://example.com/sdata/slx/system/-/")
    {
        UserName = "admin",
        Password = "password"
    };
var param = new SDataParameters {Path = "attachments('EDEMOA000001')/file"};
var results = await client.ExecuteAsync<byte[]>(param);
Console.WriteLine(results.ContentType);
using (var source = new MemoryStream(results.Content))
using (var target = File.OpenWrite(Path.GetTempFileName()))
{
    await source.CopyToAsync(target);
}

This approach doesn't provide any additional meta information such as the file's name.

If a file has an associated entity then they can both be fetched in a single request. The following example downloads an attachment just like above but also outputs the file name and description taken from the associated entity.

var param = new SDataParameters {Path = "attachments('EDEMOA000001')"};
var result = await client.ExecuteAsync<Attachment>(param);
Console.WriteLine(result.Content.FileName);
Console.WriteLine(result.Content.Description);
foreach (var file in result.Files)
{
    var filePath = Path.Combine(Path.GetTempPath(), file.FileName);
    using (var stream = File.OpenWrite(filePath))
    {
        await file.Stream.CopyToAsync(stream);
    }
}

Upload

One or more files can be attached to a request by adding an AttachedFile object to the Files collection on SDataParameters. The resulting request will be generated as a multipart MIME message that includes the main content if present along with the attached files and form-data. The following example uploads an attachment with a description specified.

var stream = File.OpenRead(@"C:\Temp\Foo.txt");
var file = new AttachedFile(null, "Foo.txt", stream);
await client.ExecuteAsync(new SDataParameters
    {
        Method = HttpMethod.Post,
        Path = "attachments",
        Content = new Attachment {Description = "Foo file"},
        ContentType = MediaType.Json,
        Files = {file}
    });

There's no need to dispose the local file stream as this will be done automatically once the request has been sent.

Clone this wiki locally