Uploading a file to HealthVault

I came across a question asking how to upload a file to HealthVault, and decided to write a quick example.

Files, like everything else in HealthVault, are stored in XML, and in fact, the File class is really a pretty thin wrapper over the underlying type. The File type stores the name of the file, the size, and the type of the content in the file.  The contents of the file is then stored in the "OtherData" member as a base-64 encoded string.

Here's some code:

FileInfo fileInfo = new FileInfo(@"C:\Documents and Settings\ericgu\My Documents\My Pictures\lame.jpg");
using (FileStream stream = System.IO.File.OpenRead(fileInfo.FullName))
{
    BinaryReader reader = new BinaryReader(stream);
    byte[] fileContents = reader.ReadBytes((int) fileInfo.Length);
    string encodedString = Convert.ToBase64String(fileContents);

    Microsoft.Health.ItemTypes.File file = new Microsoft.Health.ItemTypes.File();
file.Name = fileInfo.Name;
file.Size = fileInfo.Length;
file.ContentType = new CodableValue("image/jpg");
file.OtherData = new OtherItemData();
file.OtherData.ContentEncoding = "base-64";
    file.OtherData.ContentType = @"image/jpg";

    file.OtherData.Data = encodedString;

    PersonInfo.SelectedRecord.NewItem(file);
}

That will get the data up into HealthVault. Remember that the OtherData section doesn't come down by default, so if you want to get the contents of the file back, you'll need to specify:

filter.View.Sections =

HealthRecordItemSections.All;

(or another version of the Sections mask that includes HealthRecordItems.OtherData).