Share via


How to share files (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Users often want to share files with other people or apps. Using the sharing feature, your app can easily support tasks ranging from emailing a file to a colleague to sharing a set of pictures from a family vacation.

Files can also be shared by using Tap and send. Tap and send is sharing through Near Field Communication (NFC).

When supporting something like sharing files, you need to consider when your app can have the files ready. Most of the time, your app will probably have the files ready to go. If that's the case, the steps in this topic should be what you need. If your app needs to do some additional work before the files are ready—for example, to convert the files from one format to another—then you should take a look at our topic, How to support pull operations. That topic shows you how to use a delegate function so that target apps can pull the content being shared from your app, instead of requiring your app to push the content.

What you need to know

Technologies

Prerequisites

  • You should be familiar with Visual Studio and its templates.
  • You should be familiar with developing in C#/C++.
  • You should understand how to get files and other data, such as by using FileOpenPicker. You can learn more in Accessing files with file pickers.

Instructions

Step 1: Adding the DataTransfer namespace

You need to add the right namespaces to your app so you can create and process the objects related to sharing. At a minimum, you should add the Windows.ApplicationModel.DataTransfer namespace:

using Windows.ApplicationModel.DataTransfer;
using namespace Windows::ApplicationModel::DataTransfer;

This namespace has all you need for basic sharing. Remember, though, if you want to share content such as images or files, you'll need to add those namespaces as well. Here's a list of the namespaces you might need:

Step 2: Get the DataTransferManager object

The DataTransferManager object is the starting point for any sharing operation.

DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
DataTransferManager^ dataTransferManager = DataTransferManager::GetForCurrentView();

Step 3: Add an event handler for the DataRequested event

Add a DataRequested event handler to fire when the user wants to invoke Share. In a Windows Store app, this occurs automatically when the user invokes the Share charm. If you're developing for Windows Phone, there is no built-in Share charm, so you'll need to add a control for the user to tap and trigger the handler.

dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, 
    DataRequestedEventArgs>(this.ShareStorageItemsTextHandler);
auto dataRequestedToken = dataTransferManager->DataRequested += ref new TypedEventHandler<DataTransferManager^, 
    DataRequestedEventArgs^>(this, &MainPage::ShareStorageItemsHandler);

Step 4: Get a DataRequest object

When a DataRequested event occurs, your app receives a DataRequest object. This object contains a DataPackage that you can use to provide the content that the user wants to share.

DataRequest request = e.Request;
DataRequest^ request = e->Request;

Step 5: Set the title and description properties

The title property is mandatory and must be set.

// The title is mandatory
request.Data.Properties.Title = "Share StorageItems Example";
request.Data.Properties.Description = "Demonstrates how to share files.";
// The title is mandatory
request->Data->Properties->Title = "Share StorageItems Example";
request->Data->Properties->Description = "Demonstrates how to share files.";

Step 6: Add the files to the DataPackage.

To add the files to the DataPackage, use the SetStorageItems method.

request.Data.SetStorageItems(storageItems);
request->Data->SetStorageItems(storageItems);

Remarks

By default, SetStorageItems provides read-only "clones" of StorageItems for sharing with target apps. After you call SetStorageItems, any new properties that you set on the individual storage items won't be reflected in the cloned items. That's why you should make sure your files are completely ready for sharing before you add them to the DataPackage.

Also, if you want a target app to have read-write capabilities on the StorageItems, use the overloaded version of the SetStorageItems method that lets you specify read-only or read-write. For example, a source app that asks the target to perform a delete-on-paste operation would specify read-write so enable the target to delete the source files after copying them.

If your app needs to use an asynchronous operation to prepare the files, you’ll need to use the deferral pattern. We show how to do this in How to make asynchronous calls in your DataRequested handler.

If your app takes more than 200 milliseconds to get the files ready, you need to use a delegate function to share it. We show you how to do this in How to support pull operations. If you decide to use a delegate function, you need to set the FileTypes property on the DataPackage before adding the files themselves.

To download code that demonstrates how to share files, check out our code gallery sample.

Complete example

private void RegisterForShare()
{
    DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
    dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, 
        DataRequestedEventArgs>(this.ShareStorageItemsHandler);
}

private async void ShareStorageItemsHandler(DataTransferManager sender, 
    DataRequestedEventArgs e)
{
    DataRequest request = e.Request;
    request.Data.Properties.Title = "Share StorageItems Example";
    request.Data.Properties.Description = "Demonstrates how to share files.";
    
    // Because we are making async calls in the DataRequested event handler,
    // we need to get the deferral first.
    DataRequestDeferral deferral = request.GetDeferral();  

    // Make sure we always call Complete on the deferral.
    try
    {
        StorageFile logoFile = 
            await Package.Current.InstalledLocation.GetFileAsync("Assets\\Logo.png");
        List<IStorageItem> storageItems = new List<IStorageItem>();
        storageItems.Add(logoFile);
        request.Data.SetStorageItems(storageItems);       
    }
    finally
    {
        deferral.Complete();
    }
}
void MainPage::RegisterForShare()
{
    DataTransferManager^ dataTransferManager = DataTransferManager::GetForCurrentView();
    auto dataRequestedToken = dataTransferManager->DataRequested += 
        ref new TypedEventHandler<DataTransferManager^, DataRequestedEventArgs^>(
            this, &MainPage::ShareStorageItemsHandler);
}

void MainPage::ShareStorageItemsHandler(DataTransferManager^ sender, 
    DataRequestedEventArgs^ e)
{
    DataRequest^ request = e->Request;
    request->Data->Properties->Title = "Share StorageItems Example";
    request->Data->Properties->Description = "Demonstrates how to share files.";
    
    // Because we are making async calls in the DataRequested event handler,
    // we need to get the deferral first.
    DataRequestDeferral^ deferral = request->GetDeferral();  

    create_task(Package::Current->InstalledLocation->GetFileAsync("Assets\\Logo.png")).then(
         [this, request, deferral](task<StorageFile^> getFileTask)
    {
        try
        {
            auto logoFile = getFileTask.get();
            auto storageItems = ref new Vector<IStorageItem^>();
            storageItems->Append(logoFile);
            request->Data->SetStorageItems(storageItems);
            deferral->Complete();
        }
        catch (Exception^ ex)
        {
            // Calling FailWithDisplayText() also calls Complete on the deferral.
            request->FailWithDisplayText(ex->Message);
        }
    });
}

Sharing content source app sample

Sharing and exchanging data

How to share HTML

How to share a link

How to share text

Quickstart: Sharing content

DataPackage

Windows.ApplicationModel.DataTransfer

Windows.ApplicationModel.DataTransfer.Share

Reversi sample feature scenarios: sharing content