DownloadOperation DownloadOperation DownloadOperation DownloadOperation DownloadOperation Class

Definition

Some information relates to pre-released product which may be substantially modified before it’s commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Prerelease APIs are identified by a Prerelease label.

[Contains prerelease APIs.]
Performs an asynchronous download operation. The Background Transfer sample demonstrates this functionality. For an overview of Background Transfer capabilities, see Transferring data in the background. Download the Background Transfer sample for examples in JavaScript, C#, and C++.

public : sealed class DownloadOperation : IBackgroundTransferOperation, IBackgroundTransferOperationPriority, IDownloadOperation, IDownloadOperation2
struct winrt::Windows::Networking::BackgroundTransfer::DownloadOperation : IBackgroundTransferOperation, IBackgroundTransferOperationPriority, IDownloadOperation, IDownloadOperation2
public sealed class DownloadOperation : IBackgroundTransferOperation, IBackgroundTransferOperationPriority, IDownloadOperation, IDownloadOperation2
Public NotInheritable Class DownloadOperation Implements IBackgroundTransferOperation, IBackgroundTransferOperationPriority, IDownloadOperation, IDownloadOperation2
// This class does not provide a public constructor.
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
internetClientServer privateNetworkClientServer internetClient

Examples

The following example demonstrates how to configure and begin a basic download operation, and is based on the Background Transfer sample offered in the Windows Sample Gallery.

        var download = null;
        var promise = null;

        function DownloadFile (uriString, fileName) {
            try {
                // Asynchronously create the file in the pictures folder.
                Windows.Storage.KnownFolders.picturesLibrary.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (newFile) {
                    var uri = Windows.Foundation.Uri(uriString);
                    var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();

                    // Create a new download operation.
                    download = downloader.createDownload(uri, newFile);

                    // Start the download and persist the promise to be able to cancel the download.
                    promise = download.startAsync().then(complete, error, progress);
                }, error);
            } catch (err) {
                displayException(err);
            }
        };
       using Windows.Foundation;
       using Windows.Networking.BackgroundTransfer;
       using Windows.Storage;

       private async void StartDownload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Uri source = new Uri(serverAddressField.Text.Trim());
                string destination = fileNameField.Text.Trim();

                StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    destination, CreationCollisionOption.GenerateUniqueName);

                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation download = downloader.CreateDownload(source, destinationFile);

                // Attach progress and completion handlers.
                HandleDownloadAsync(download, true);
            }
            catch (Exception ex)
            {
                LogException("Download Error", ex);
            }
        }

Remarks

After app termination, an app should enumerate all existing DownloadOperation instances at next start-up using GetCurrentDownloadsAsync. When a UWP app using Background Transfer is terminated, incomplete downloads will persist in the background. If the app is restarted after termination and these incomplete operations are not enumerated and re-introduced to the current session, they will go stale and continue to occupy device resources.

Background transfer doesn't support concurrent downloads of the same Uri. So an app can download http://example.com/myfile.wmv once, or download it again after a previous download completed. An app shouldn't start two downloads of the same Uri concurrently, since this may result in truncated files.

Note

Paused or incomplete download operations can only be resumed if the server accepts range-requests.

Timeout considerations

  • 1.) When establishing a new connection for a download over TCP/SSL, the connection attempt is aborted if not established within five minutes.
  • 2.) After the connection has been established, an HTTP request message that has not received a response within two minutes is aborted. Assuming there is Internet connectivity, Background Transfer will retry a download up to three times. In the event Internet connectivity is not detected, additional attempts will not be made until it is.

Debugging Guidance

Stopping a debugging session in Microsoft Visual Studio is comparable to closing your app; downloads are paused and POST uploads are terminated. Even while debugging, your app should enumerate and then pause, resume, restart, or cancel any persisted downloads.

However, if Microsoft Visual Studio project updates, like changes to the app manifest, require that the app is uninstalled and re-deployed for debugging, GetCurrentDownloadsAsync cannot enumerate persisted operations created using the previous app deployment.

Properties

CostPolicy CostPolicy CostPolicy CostPolicy CostPolicy

Gets and sets the cost policy for the download.

public : BackgroundTransferCostPolicy CostPolicy { get; set; }
BackgroundTransferCostPolicy CostPolicy(); void CostPolicy(BackgroundTransferCostPolicy costpolicy);
public BackgroundTransferCostPolicy CostPolicy { get; set; }
Public ReadWrite Property CostPolicy As BackgroundTransferCostPolicy
var backgroundTransferCostPolicy = downloadOperation.costPolicy;
downloadOperation.costPolicy = backgroundTransferCostPolicy;
Value
BackgroundTransferCostPolicy BackgroundTransferCostPolicy BackgroundTransferCostPolicy

Specifies whether the transfer can happen over costed networks.

CurrentWebErrorStatus CurrentWebErrorStatus CurrentWebErrorStatus CurrentWebErrorStatus CurrentWebErrorStatus

A transfer's WebErrorStatus, which can be monitored during the lifetime of the DownloadOperation.

public : IReference<WebErrorStatus> CurrentWebErrorStatus { get; }
IReference<WebErrorStatus> CurrentWebErrorStatus();
public Nullable<WebErrorStatus> CurrentWebErrorStatus { get; }
Public ReadOnly Property CurrentWebErrorStatus As Nullable<WebErrorStatus>
var nullable = downloadOperation.currentWebErrorStatus;
Value
Nullable<WebErrorStatus> Nullable<WebErrorStatus> Nullable<WebErrorStatus>

A WebErrorStatus error.

Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)
Capabilities
internetClientServer privateNetworkClientServer internetClient

Examples

WebErrorStatus, DownloadOperation

Group Group Group Group Group

Note

Group may be altered or unavailable for releases after Windows 8.1. Instead, use TransferGroup.

Gets a string value indicating the group the transfer belongs to.

public : Platform::String Group { get; }
winrt::hstring Group();
public string Group { get; }
Public ReadOnly Property Group As string
var string = downloadOperation.group;
Value
string string string

The group name.

Guid Guid Guid Guid Guid

This is a unique identifier for a specific download operation. A GUID associated to a download operation will not change for the duration of the download.

public : Platform::Guid Guid { get; }
Guid Guid();
public Guid Guid { get; }
Public ReadOnly Property Guid As Guid
var guid = downloadOperation.guid;
Value
Guid Guid Guid

The unique ID for this download operation.

IsRandomAccessRequired IsRandomAccessRequired IsRandomAccessRequired IsRandomAccessRequired IsRandomAccessRequired

A boolean property to enable random access. The property must be set to TRUE before calling StartAsync() on a DownloadOperation object to use the random access feature. After calling StartAsync(), call GetResultRandomAccessStreamReference to get a reference to the random access stream and read from it.

public : Platform::Boolean IsRandomAccessRequired { get; set; }
bool IsRandomAccessRequired(); void IsRandomAccessRequired(bool israndomaccessrequired);
public bool IsRandomAccessRequired { get; set; }
Public ReadWrite Property IsRandomAccessRequired As bool
var bool = downloadOperation.isRandomAccessRequired;
downloadOperation.isRandomAccessRequired = bool;
Value
bool bool bool

TRUE to use the random access feature. The default value is FALSE.

Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)
Capabilities
internetClientServer privateNetworkClientServer internetClient

Remarks

The IsRandomAccessRequired setter will fail with E_ILLEGAL_METHOD_CALL and a custom error message if StartAsync() has already been called on the DownloadOperation.

See Also

Method Method Method Method Method

Gets the method to use for the download.

public : Platform::String Method { get; }
winrt::hstring Method();
public string Method { get; }
Public ReadOnly Property Method As string
var string = downloadOperation.method;
Value
string string string

The method to use for the download. This value can be GET, PUT, RETR, or STOR.

Priority Priority Priority Priority Priority

Gets or sets the transfer priority of this download operation when within a BackgroundTransferGroup. Possible values are defined by BackgroundTransferPriority.

public : BackgroundTransferPriority Priority { get; set; }
BackgroundTransferPriority Priority(); void Priority(BackgroundTransferPriority priority);
public BackgroundTransferPriority Priority { get; set; }
Public ReadWrite Property Priority As BackgroundTransferPriority
var backgroundTransferPriority = downloadOperation.priority;
downloadOperation.priority = backgroundTransferPriority;
See Also

Progress Progress Progress Progress Progress

Gets the current progress of the upload operation.

public : BackgroundDownloadProgress Progress { get; }
BackgroundDownloadProgress Progress();
public BackgroundDownloadProgress Progress { get; }
Public ReadOnly Property Progress As BackgroundDownloadProgress
var backgroundDownloadProgress = downloadOperation.progress;

Remarks

The value of the Progress property is updated in real time, which means that the value can change while a progress handler is executing. As a best practice, create a local copy of the Progress property at the beginning of your progress handler, and use only that copy in your progress handler, to maintain a consistent view of progress as your handler executes.

See Also

RecoverableWebErrorStatuses RecoverableWebErrorStatuses RecoverableWebErrorStatuses RecoverableWebErrorStatuses RecoverableWebErrorStatuses

A set of WebErrorStatus values that applications anticipate the download will hit, and that the applications know how to handle.

public : IVector<WebErrorStatus> RecoverableWebErrorStatuses { get; }
IVector<WebErrorStatus> RecoverableWebErrorStatuses();
public IList<WebErrorStatus> RecoverableWebErrorStatuses { get; }
Public ReadOnly Property RecoverableWebErrorStatuses As IList<WebErrorStatus>
var iList = downloadOperation.recoverableWebErrorStatuses;
Value
IList<WebErrorStatus> IList<WebErrorStatus> IList<WebErrorStatus>

A set of WebErrorStatus values.

Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)
Capabilities
internetClientServer privateNetworkClientServer internetClient

RequestedUri RequestedUri RequestedUri RequestedUri RequestedUri

Gets the URI from which to download the file.

public : Uri RequestedUri { get; }
Uri RequestedUri();
public Uri RequestedUri { get; }
Public ReadOnly Property RequestedUri As Uri
var uri = downloadOperation.requestedUri;
Value
Uri Uri Uri

The URI to download from.

Remarks

The URI can be updated in for transfers that have hit a recoverable error (PausedRecoverableWebErrorStatus), or that have explicitly paused by the app (PausedByApplication). Once the URI has been updated, the app must call DownloadOperation.Resume to initiate a retry.

Due to OS limitations, downloads that don't opt into random access mode will always restart from scratch whenever their URL is updated. To opt into random access mode, set DownloadOperation.IsRandomAccessRequired to true. Transfers configured that way have full support for resumable URL updates. If the timestamp or file size of the updated URL is different from that of the previous URL, the download will restart from scratch. Otherwise, the transfer will resume from the same position using the new URL.

See Also

ResultFile ResultFile ResultFile ResultFile ResultFile

Returns the IStorageFile object provided by the caller when creating the DownloadOperation object using CreateDownload.

public : IStorageFile ResultFile { get; }
IStorageFile ResultFile();
public IStorageFile ResultFile { get; }
Public ReadOnly Property ResultFile As IStorageFile
var iStorageFile = downloadOperation.resultFile;
Value
IStorageFile IStorageFile IStorageFile

The returned file object.

TransferGroup TransferGroup TransferGroup TransferGroup TransferGroup

Gets the group that this download operation belongs to.

public : BackgroundTransferGroup TransferGroup { get; }
BackgroundTransferGroup TransferGroup();
public BackgroundTransferGroup TransferGroup { get; }
Public ReadOnly Property TransferGroup As BackgroundTransferGroup
var backgroundTransferGroup = downloadOperation.transferGroup;
See Also

Methods

AttachAsync() AttachAsync() AttachAsync() AttachAsync() AttachAsync()

Returns an asynchronous operation that can be used to monitor progress and completion of the attached download. Calling this method allows an app to attach download operations that were started in a previous app instance.

public : IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> AttachAsync()
IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> AttachAsync() const;
public IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> AttachAsync()
Public Function AttachAsync() As IAsyncOperationWithProgress( Of DownloadOperation )( Of DownloadOperation )
Windows.Networking.BackgroundTransfer.DownloadOperation.attachAsync().done( /* Your success and error handlers */ );
Returns

Examples


        function AttachDownload (loadedDownload) {
            try {
                download = loadedDownload;
                promise = download.attachAsync().then(complete, error, progress);
            } catch (err) {
                displayException(err);
            }
        };

Remarks

Exceptions

COMException

Thrown when a feature-specific HRESULT is returned from a method call.

This is the most common exception that is thrown by networking methods. An app should use the HRESULT from the exception to determine the cause of the error. For more information on specific errors, see the Error Codes section below.

AccessDeniedException

Thrown when access is denied to a resource or feature. This exception occurs when an app doesn't have the required network capabilities set in the app manifest for the network operation requested.

InvalidArgumentException

Thrown when one of the arguments that are provided to a method is not valid.

If user-supplied input caused this exception, an app could inform the user and request new input.

ObjectDisposedException

Thrown when an operation is performed on a disposed object.

OutOfMemoryException

Thrown when insufficient memory is available to complete the operation.

While, this method can be called from multiple app instances, developers should not attach callbacks from the primary app instance in a background task. This will cause BackgroundTransferHost.exe to hang.

GetDownloadedRanges() GetDownloadedRanges() GetDownloadedRanges() GetDownloadedRanges() GetDownloadedRanges()

Returns the full list of file ranges that have been downloaded so far.

public : IVector<BackgroundTransferFileRange> GetDownloadedRanges()
IVector<BackgroundTransferFileRange> GetDownloadedRanges() const;
public IList<BackgroundTransferFileRange> GetDownloadedRanges()
Public Function GetDownloadedRanges() As IList<BackgroundTransferFileRange>( Of BackgroundTransferFileRange )
var iVector = downloadOperation.getDownloadedRanges();
Returns
IList<BackgroundTransferFileRange> IList<BackgroundTransferFileRange> IList<BackgroundTransferFileRange>

Returns an IVector.

Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)
Capabilities
internetClientServer privateNetworkClientServer internetClient

GetResponseInformation() GetResponseInformation() GetResponseInformation() GetResponseInformation() GetResponseInformation()

Gets the response information.

public : ResponseInformation GetResponseInformation()
ResponseInformation GetResponseInformation() const;
public ResponseInformation GetResponseInformation()
Public Function GetResponseInformation() As ResponseInformation
var responseInformation = downloadOperation.getResponseInformation();
Returns

Contains the data returned by a server response.

Remarks

This method returns an object that contains information about the current server response. When calling this method multiple times, the object returned will be the same as long as there is no new server response information available. Sometimes however, one download consists of multiple requests to a server. If a request gets aborted due to some non-fatal error (e.g. machine lost internet connectivity, cost policy required download to pause, application called Pause(), etc.), Download API will invoke a new request and try to resume/restart the download. The response information from the server for this second request may be different than the one returned by the first request.

Returns null if any of the following conditions is true.

  • The transfer associated with the DownloadOperation is being made using a protocol other than HTTP (e.g., FTP).
  • The DownloadOperation hasn't yet begun.
  • There was a failure before any response from the server was received (e.g., connection couldn't be established).

GetResultRandomAccessStreamReference() GetResultRandomAccessStreamReference() GetResultRandomAccessStreamReference() GetResultRandomAccessStreamReference() GetResultRandomAccessStreamReference()

Gets a reference to the random access stream and reads from it. It's necessary to set IsRandomAccessRequired to TRUE before calling GetResultRandomAccessStreamReference.

public : IRandomAccessStreamReference GetResultRandomAccessStreamReference()
IRandomAccessStreamReference GetResultRandomAccessStreamReference() const;
public IRandomAccessStreamReference GetResultRandomAccessStreamReference()
Public Function GetResultRandomAccessStreamReference() As IRandomAccessStreamReference
var iRandomAccessStreamReference = downloadOperation.getResultRandomAccessStreamReference();
Returns
Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)
Capabilities
internetClientServer privateNetworkClientServer internetClient
See Also

GetResultStreamAt(UInt64) GetResultStreamAt(UInt64) GetResultStreamAt(UInt64) GetResultStreamAt(UInt64) GetResultStreamAt(UInt64)

Gets the partially downloaded response at the specified position.

public : IInputStream GetResultStreamAt(unsigned __int64 position)
IInputStream GetResultStreamAt(UInt64 position) const;
public IInputStream GetResultStreamAt(UInt64 position)
Public Function GetResultStreamAt(position As UInt64) As IInputStream
var iInputStream = downloadOperation.getResultStreamAt(position);
Parameters
position
UInt64 UInt64 UInt64

The position at which to start reading.

Returns

MakeCurrentInTransferGroup() MakeCurrentInTransferGroup() MakeCurrentInTransferGroup() MakeCurrentInTransferGroup() MakeCurrentInTransferGroup()

Prerelease. Prioritizes the download transfer operation (and any transfers that follow it in the same transfer group). Calling this method on a transfer that doesn't belong to a transfer group has no effect.

public : void MakeCurrentInTransferGroup()
void MakeCurrentInTransferGroup() const;
public void MakeCurrentInTransferGroup()
Public Function MakeCurrentInTransferGroup() As void
downloadOperation.makeCurrentInTransferGroup();
Additional features and requirements
Device family
Windows 10 Insider Preview (introduced v10.0.17095.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v6)
Capabilities
internetClientServer privateNetworkClientServer internetClient

Pause() Pause() Pause() Pause() Pause()

Pauses a download operation.

public : void Pause()
void Pause() const;
public void Pause()
Public Function Pause() As void
downloadOperation.pause();

Remarks

Calling this method will abort the HTTP request but preserve state for the download and the partially downloaded response. This method will fail when called for operations that haven't been started yet, are already paused, or use POST requests.

See Also

Resume() Resume() Resume() Resume() Resume()

Resumes a paused download operation.

public : void Resume()
void Resume() const;
public void Resume()
Public Function Resume() As void
downloadOperation.resume();

Remarks

This method can be called on a paused download operation to resume the download. The download operation will try to resume the download if possible. Only requests where the server accepts range-requests can resume. Otherwise the download is restarted.

See Also

StartAsync() StartAsync() StartAsync() StartAsync() StartAsync()

Starts an asynchronous download operation.

public : IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> StartAsync()
IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> StartAsync() const;
public IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> StartAsync()
Public Function StartAsync() As IAsyncOperationWithProgress( Of DownloadOperation )( Of DownloadOperation )
Windows.Networking.BackgroundTransfer.DownloadOperation.startAsync().done( /* Your success and error handlers */ );
Returns

Remarks

Exceptions

COMException

Thrown when a feature-specific HRESULT is returned from a method call.

This is the most common exception that is thrown by networking methods. An app should use the HRESULT from the exception to determine the cause of the error. For more information on specific errors, see the Error Codes section below.

AccessDeniedException

Thrown when access is denied to a resource or feature. This exception occurs when an app doesn't have the required network capabilities set in the app manifest for the network operation requested.

InvalidArgumentException

Thrown when one of the arguments that are provided to a method is not valid.

If user-supplied input caused this exception, an app could inform the user and request new input.

ObjectDisposedException

Thrown when an operation is performed on a disposed object.

OutOfMemoryException

Thrown when insufficient memory is available to complete the operation.

Background transfer doesn't support concurrent downloads of the same Uri. So an app can download http://example.com/myfile.wmv once, or download it again after a previous download completed. An app shouldn't start two downloads of the same Uri concurrently, since this may result in truncated files.

A download operation must be scheduled using one of the BackgroundDownloader.CreateDownload or BackgroundDownloader.CreateDownloadAsync methods before the StartAsync method is called.

Important

Queuing up a large number of transfers on the main UI thread can result in degraded performance of your app's UI, even though the call is awaitable. If you are queuing up a large number of transfers, it is recommended that you call StartAsync on a background worker thread as in the following example.

operation = await Task.Run(() => { return myDownloadOperation.StartAsync(); });
See Also

Events

RangesDownloaded RangesDownloaded RangesDownloaded RangesDownloaded RangesDownloaded

Provides access to to incremental download progress.

public : event TypedEventHandler RangesDownloaded<DownloadOperation, BackgroundTransferRangesDownloadedEventArgs>
// Register
event_token RangesDownloaded(TypedEventHandler<DownloadOperation, BackgroundTransferRangesDownloadedEventArgs> const& handler) const;

// Revoke with event_token
void RangesDownloaded(event_token const& cookie) const;

// Revoke with event_revoker
RangesDownloaded_revoker RangesDownloaded(auto_revoker_t, TypedEventHandler<DownloadOperation, BackgroundTransferRangesDownloadedEventArgs> const& handler) const;
public event TypedEventHandler RangesDownloaded<DownloadOperation, BackgroundTransferRangesDownloadedEventArgs>
Public Event TypedEventHandler RangesDownloaded( Of ( Of DownloadOperation ), ( Of BackgroundTransferRangesDownloadedEventArgs ))
function onRangesDownloaded(eventArgs){/* Your code */}


downloadOperation.addEventListener("rangesDownloaded", onRangesDownloaded);
downloadOperation.removeEventListener("rangesDownloaded", onRangesDownloaded);
Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)
Capabilities
internetClientServer privateNetworkClientServer internetClient

See Also