---
source_url: https://www.pubnub.com/docs/sdks/unity/api-reference/files
title: File Sharing API for Unity SDK
updated_at: 2026-05-22T11:07:58.541Z
sdk_name: PubNub Unity SDK
sdk_version: v9.3.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# File Sharing API for Unity SDK

PubNub Unity SDK, use the latest version: v9.3.0

You can upload and share files up to 5 MB on PubNub. Common uses include sharing images in chat apps and documents in healthcare.

When a file is uploaded on a `channel`, it's stored and managed using a storage service, and associated with your key. Subscribers to that `channel` receive a file event which contains a file `ID`, `filename`, and optional `description`.

## Send file

Upload the file to a specified channel.

This method covers the entire process of sending a file, including preparation, uploading the file to a cloud storage service, and post-uploading messaging on a channel.

For the last messaging step, `SendFile` internally calls the [PublishFileMessage](#publish-file-message) method to publish a message on the channel.

The published message contains metadata about the file, such as the file identifier and name, enabling others on the channel to find out about the file and access it.

For details on the method that publishes the file message, see [Publish file message](#publish-file-message).

### Method(s)

```csharp
pubnub.SendFile()
    .Channel(string)
    .File(string|byte[])
    .Texture(Texture2D | RenderTexture)
    .FileName(string)
    .Ttl(int)
    .ShouldStore(bool)
    .Message(string)
    .Meta(Dictionary<string, object>)
    .CustomMessageType(string)
    .Execute(System.Action<PNFileUploadResult, PNStatus>)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| Channel | string | Yes |  | `Channel` for the file. |
| File | string | Optional |  | Full path of the file with file name or an array of bytes. When using an array of bytes, you must set `FileName`. |
| Texture | Texture2D | Optional |  | An instance of a `Texture` object. When you send a `Texture`, a `Message` with its size and format is added automatically. |
| FileName | string | Optional |  | Name of the file to send. You can use it to override the default file name. |
| TTL | int | Optional |  | How long the message should be stored in the channel's storage. |
| ShouldStore | bool | Optional |  | Whether to store the published file message in the channel's history. |
| Message | string | Optional |  | Message which should be sent along with file to specified `channel`. |
| Meta | Dictionary<string, | Optional |  | Dictionary`<string, object>` with values which should be used by PubNub service to filter file messages. |
| CustomMessageType | string | Optional |  | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes `-` and underscores `_` are allowed. The value cannot start with special characters or the string `pn_` or `pn-`. Examples: `text`, `action`, `poll`. |
| Execute | System.Action | Yes |  | `System.Action` of type `PNFileUploadResult`. |
| ExecuteAsync | None | Optional |  | Returns `Task<PNResult<PNFileUploadResult>>`. |

:::warning Deprecated parameter
The `CipherKey` parameter in this method is deprecated. We recommend that you configure the [crypto module](https://www.pubnub.com/docs/sdks/unity/api-reference/configuration#cryptomodule) on your PubNub instance instead. If you pass `CipherKey` as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
:::

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```csharp
using PubnubApi;
using PubnubApi.Unity;
using UnityEngine;

public class SendFileExample : MonoBehaviour {
	// Reference to a pubnub manager previously setup in Unity Editor
	// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
	[SerializeField] private PNManagerBehaviour pubnubManager;

	// An editor-serialized string for the channel ID
	[SerializeField] private string channelId = "my_channel";

	// An editor-serialized string for the file path
	[SerializeField] private string filePath = "cat_picture.jpg";

	// An editor-serialized string for the cipher key
	[SerializeField] private string cipherKey = "my_cipher_key";

	private async void Start() {
		// Getting a reference to the Pubnub instance
		var pubnub = pubnubManager.pubnub;

		// Note that you can also initialize Pubnub instance for Unity directly from code:
		/*
		PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
		{
			SubscribeKey = "demo",
			PublishKey = "demo",
		};
		Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);
		*/

		// Sending a file to the specified channel
		var fileUploadResponse = await pubnub.SendFile()
			.Channel(channelId)
			.File(filePath) // checks the bin folder if no path is provided
			.CipherKey(cipherKey) // Deprecated: Prefer setting up in PubNub config
			.Message("Look at this photo!")
			.CustomMessageType("file-message")
			.ExecuteAsync();

		// Extracting the result and status
		var fileUploadResult = fileUploadResponse.Result;
		var fileUploadStatus = fileUploadResponse.Status;

		// Handling errors and logging results
		if (!fileUploadStatus.Error && fileUploadResult != null) {
			Debug.Log($"File uploaded successfully: {pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadResult)}");
		} else {
			Debug.LogError($"Error uploading file: {pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadStatus)}");
		}
	}
}
```

### Response

```csharp
{
    "Timetoken":15957709330808500,
    "FileId":"d9515cb7-48a7-41a4-9284-f4bf331bc770",
    "FileName":"cat_picture.jpg"
}
```

### Returns

The `SendFile()` operation returns a `PNResult<PNFileUploadResult>` which contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `Result` | PNFileUploadResult | Returns a `PNFileUploadResult` object. |
| `Status` | PNStatus | Returns a `PNStatus` object. |

`PNFileUploadResult` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `Timetoken` | long | Returns a `PNFileUploadResult` object. |
| `FileId` | string | Returns the `ID` of the file. |
| `FileName` | string | Returns the `name` of the file. |

### Other examples

#### Send file with push notification

:::tip Trigger push notifications when sharing files
To send mobile push notifications when sharing a file, include `pn_apns` (for iOS) and/or `pn_fcm` (for Android) payloads in the `message` parameter of the `SendFile` method.
When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.
:::

```csharp
var message = new MobilePushHelper()
              .PushTypeSupport(new [] { PNPushType.APNS2, PNPushType.FCM })
              .Title("New File")
              .Body("Check out this file!")
              .Apns2Data(new List<Apns2Data>()
              {
                  new ()
                  {
                      targets = new List<PushTarget>()
                      {
                          new ()
                          {
                              environment = Environment.Production,
                              topic = "com.yourapp.bundleid"
                          }
                      }
                  }
              }).GetPayload();

PNResult<PNFileUploadResult> fileResult = await pubnub.SendFile()
  .Channel("my-channel")
  .File(fileContent)
  .FileName("example.txt")
  .Message(message)
  .ExecuteAsync();
```

For more details on push notification payload structure, see the [iOS Push](https://www.pubnub.com/docs/general/push/ios) and [Android Push](https://www.pubnub.com/docs/general/push/android) documentation. To prevent the sender from receiving their own push notification, add their device token to `excluded_devices` in the `pn_push` targets.

## List channel files

Retrieve a list of files uploaded to a `channel`.

### Method(s)

```csharp
pubnub.ListFiles()
    .Channel(string)
    .Limit(int)
    .Next(string)
    .QueryParam(Dictionary<string, object>)
    .Execute(System.Action<PNListFilesResult, PNStatus>)
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: stringDefault: n/a | `Channel` to get list of files. |
| `Limit`Type: intDefault: 100 | Number of files to return. |
| `Next`Type: stringDefault: n/a | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |
| `QueryParam`Type: Dictionary`<string, object>`Default: n/a | Dictionary `object` to pass name/value pairs as query `string` params with PubNub URL request for debug purpose. |
| `Execute` *Type: `System.Action`Default: n/a | `System.Action` of type `PNListFilesResult`. |
| `ExecuteAsync`Type: NoneDefault: n/a | Returns `Task<PNResult<PNListFilesResult>>`. |

### Sample code

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
    SubscribeKey = "demo",
    PublishKey = "demo",
    Secure = true
};

Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);

// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
/*
[SerializeField] private PNManagerBehaviour pubnubManager;
Pubnub pubnub = pubnubManager.pubnub;
*/

PNResult<PNListFilesResult> listFilesResponse = await pubnub.ListFiles()
    .Channel("my_channel")
    .ExecuteAsync();
PNListFilesResult listFilesResult = listFilesResponse.Result;
PNStatus listFilesStatus = listFilesResponse.Status;
if (!listFilesStatus.Error && listFilesResult != null)
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(listFilesResult));
}
else
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(listFilesStatus));
}
```

### Response

```csharp
{
    "FilesList":[
    {
        "Name":"cat_picture.jpg",
        "Id":"d9515cb7-48a7-41a4-9284-f4bf331bc770",
        "Size":25778,
        "Created":"2020-07-26T13:42:06Z"
    }],
    "Count":1,
    "Next":null
}
```

### Returns

Returns `PNResult<PNListFilesResult>`.

| Property Name | Type | Description |
| --- | --- | --- |
| `Result` | PNListFilesResult | Returns a `PNListFilesResult` object. |
| `Status` | PNStatus | Returns a `PNStatus` object. |

`PNListFilesResult` fields:

| Property Name | Type | Description |
| --- | --- | --- |
| `FilesList` | list`<PNFileResult>` | `List` of channel files. |
| `Count` | int | Number of files returned. |
| `Next` | string | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |

`PNFileResult` fields:

| Property Name | Type | Description |
| --- | --- | --- |
| `Name` | string | `Name` of the file. |
| `Id` | string | `ID` of the file. |
| `Size` | int | `Size` of the file. |
| `Created` | string | Create date of the file. |

## Get file URL

Generate a URL to download a file from the target `channel`.

### Method(s)

```csharp
pubnub.GetFileUrl()
    .Channel(string)
    .FileId(string)
    .FileName(string)
    .Execute(System.Action<PNFileUrlResult, PNStatus>)
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: string | Name of `channel` within which file with name has been uploaded. |
| `FileId` *Type: string | Unique file identifier which has been assigned during file upload. |
| `FileName` *Type: string | Name under which uploaded file is stored for `channel`. |
| `Execute` *Type: `System.Action` | `System.Action` of type `PNFileUrlResult`. |
| `ExecuteAsync`Type: None | Returns `Task<PNResult<PNFileUrlResult>>`. |

### Sample code

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
    SubscribeKey = "demo",
    PublishKey = "demo",
    Secure = true
};

Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);

// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
/*
[SerializeField] private PNManagerBehaviour pubnubManager;
Pubnub pubnub = pubnubManager.pubnub;
*/

PNResult<PNFileUrlResult> getFileUrlResponse = await pubnub.GetFileUrl()
    .Channel("my_channel")
    .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
    .FileName("cat_picture.jpg")
    .ExecuteAsync();
PNFileUrlResult getFileUrlResult = getFileUrlResponse.Result;
PNStatus getFileUrlStatus = getFileUrlResponse.Status;
if (!getFileUrlStatus.Error && getFileUrlResult != null)
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlResult));
}
else
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlStatus));
}
```

### Returns

Returns `PNResult<PNFileUrlResult>`.

| Property Name | Type | Description |
| --- | --- | --- |
| `Result` | PNFileUrlResult | Returns a `PNFileUrlResult` object. |
| `Status` | PNStatus | Returns a `PNStatus` object. |

`PNFileUrlResult` fields:

| Property Name | Type | Description |
| --- | --- | --- |
| `Url` | string | `URL` which can be used to download remote file with specified name and identifier. |

## Download file

Download a file from the specified `channel`.

### Method(s)

```csharp
pubnub.DownloadFile()
    .Channel(string)
    .FileId(string)
    .FileName(string)
    .Execute(System.Action<PNDownloadFileResult, PNStatus>)
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: string | Name of `channel` within which file with name has been uploaded. |
| `FileId` *Type: string | Unique file identifier which has been assigned during file upload. |
| `FileName` *Type: string | Name under which uploaded file is stored for `channel`. |
| `Execute` *Type: `System.Action` | `System.Action` of type `PNDownloadFileResult`. |
| `ExecuteAsync`Type: None | Returns `Task<PNResult<PNDownloadFileResult>>`. |

:::warning Deprecated parameter
The `CipherKey` parameter in this method is deprecated. We recommend that you configure the [crypto module](https://www.pubnub.com/docs/sdks/unity/api-reference/configuration#cryptomodule) on your PubNub instance instead. If you pass `CipherKey` as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
:::

### Sample code

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
    SubscribeKey = "demo",
    PublishKey = "demo",
    Secure = true
};

Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);

// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
/*
[SerializeField] private PNManagerBehaviour pubnubManager;
Pubnub pubnub = pubnubManager.pubnub;
*/

PNResult<PNDownloadFileResult> fileDownloadResponse = await pubnub.DownloadFile()
    .Channel("my_channel")
    .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
    .FileName("cat_picture.jpg")
    .ExecuteAsync();
PNDownloadFileResult fileDownloadResult = fileDownloadResponse.Result;
PNStatus fileDownloadStatus = fileDownloadResponse.Status;
if (!fileDownloadStatus.Error && fileDownloadResult != null)
{
    fileDownloadResult.SaveFileToLocal(downloadUrlFileName); //saves to bin folder if no path is provided
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadResult.FileName));
}
else
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadStatus));
}
```

### Response

```csharp
{
    //Call fileDownloadResult.SaveFileToLocal(<destination path>) to save file.
    "FileBytes":"/9j/4AAQSkZJRgABAQEAkACQAAD/4RCERXhpZgAATU0AKgAAAAgABAE7AAIAAAAGAAAISodpAAQAAAABAAAIUJydAAEAAAA...<truncated due to lengthy data",
    "FileName":"cat_picture.jpg"
}
```

### Returns

Returns `PNResult<PNDownloadFileResult>`.

| Property Name | Type | Description |
| --- | --- | --- |
| `Result` | PNDownloadFileResult | Returns a `PNDownloadFileResult` object. |
| `Status` | PNStatus | Returns a `PNStatus` object. |

`PNDownloadFileResult` fields:

| Property Name | Type | Description |
| --- | --- | --- |
| `FileBytes` | byte[] | Bytes of the downloaded file. |
| `FileName` | string | Name of the downloaded file. |
| `SaveFileToLocal(string)` | n/a | Call with a destination path to save the file locally. |

## Delete file

Delete a file from the specified `channel`.

### Method(s)

```csharp
pubnub.DeleteFile()
    .Channel(string)
    .FileId(string)
    .FileName(string)
    .Execute(System.Action<PNDeleteFileResult, PNStatus>)
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: string | Name of `channel` within which file with name needs to be deleted. |
| `FileId` *Type: string | Unique file identifier of the file to be deleted. |
| `FileName` *Type: string | Name of the file to be deleted from the `channel`. |
| `Execute` *Type: `System.Action` | `System.Action` of type `PNDeleteFileResult`. |
| `ExecuteAsync`Type: None | Returns `Task<PNResult<PNDeleteFileResult>>`. |

### Sample code

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
    SubscribeKey = "demo",
    PublishKey = "demo",
    Secure = true
};

Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);

// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
/*
[SerializeField] private PNManagerBehaviour pubnubManager;
Pubnub pubnub = pubnubManager.pubnub;
*/

PNResult<PNDeleteFileResult> deleteFileResponse = await pubnub.DeleteFile()
    .Channel("my_channel")
    .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
    .FileName("cat_picture.jpg")
    .ExecuteAsync();
PNDeleteFileResult deleteFileResult = deleteFileResponse.Result;
PNStatus deleteFileStatus = deleteFileResponse.Status;
if (!deleteFileStatus.Error && deleteFileResult != null)
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(deleteFileResult));
}
else
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(deleteFileStatus));
}
```

### Response

```csharp
{}
```

### Returns

Returns `PNResult<PNDeleteFileResult>`.

| Property Name | Type | Description |
| --- | --- | --- |
| `Result` | PNDeleteFileResult | Returns a `PNDeleteFileResult` object. |
| `Status` | PNStatus | Returns a `PNStatus` object. |

`PNDeleteFileResult` is empty.

## Publish file message

Publish the uploaded file message to a specified channel.

This method is called internally by [SendFile](#send-file) as part of the file-sending process to publish the message with the file (already uploaded in a storage service) on a channel.

This message includes the file's unique identifier and name elements, which are needed to construct download links and inform channel subscribers that the file is available for download.

You can call this method when `SendFile` fails and returns the `status.operation === PNPublishFileMessageOperation` error. In that case, you can use the data from the `status` object to try again and use `PublishFileMessage` to manually resend a file message to a channel without repeating the upload step.

### Method(s)

```csharp
pubnub.PublishFileMessage()
    .Channel(string)
    .FileId(string)
    .FileName(string)
    .Message(object)
    .Meta(Dictionary<string, object>)
    .ShouldStore(bool)
    .CustomMessageType(string)
    .Execute(System.Action<PNPublishFileMessageResult, PNStatus>)
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: stringDefault: n/a | Name of `channel` to publish file message |
| `FileId` *Type: stringDefault: n/a | Unique file identifier of the file. |
| `FileName` *Type: stringDefault: n/a | Name of the file. |
| `Message`Type: stringDefault: n/a | The payload. |
| `Meta`Type: stringDefault: n/a | Metadata object which can be used with the filtering ability. |
| `ShouldStore`Type: boolDefault: `true` | Whether to store the message in history. |
| `CustomMessageType`Type: stringDefault: n/a | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes `-` and underscores `_` are allowed. The value cannot start with special characters or the string `pn_` or `pn-`. Examples: `text`, `action`, `poll`. |
| `Execute` *Type: `System.Action`Default: n/a | `System.Action` of type `PNPublishFileMessageResult`. |
| `ExecuteAsync`Type: NoneDefault: n/a | Returns `Task<PNResult<PNPublishFileMessageResult>>`. |

### Sample code

```csharp
using PubnubApi;
using PubnubApi.Unity;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
    SubscribeKey = "demo",
    PublishKey = "demo",
    Secure = true
};

Pubnub pubnub = PubnubUnityUtils.NewUnityPubnub(pnConfiguration);

// If you're using Unity Editor setup you can get the Pubnub instance from PNManagerBehaviour
// For more details, see https://www.pubnub.com/docs/sdks/unity#configure-pubnub
/*
[SerializeField] private PNManagerBehaviour pubnubManager;
Pubnub pubnub = pubnubManager.pubnub;
*/

PNResult<PNPublishFileMessageResult> publishFileMsgResponse = await pubnub.PublishFileMessage()
    .Channel("my_channel")
    .FileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
    .FileName("cat_picture.jpg") //checks the bin folder if no path is provided
    .Message("This is a sample message")
    .CustomMessageType("file-message")
    .ExecuteAsync();
PNPublishFileMessageResult publishFileMsgResult = publishFileMsgResponse.Result;
PNStatus publishFileMsgStatus = publishFileMsgResponse.Status;
if (!publishFileMsgStatus.Error && publishFileMsgResult != null)
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(publishFileMsgResult));
}
else
{
    Debug.Log(pubnub.JsonPluggableLibrary.SerializeToJsonString(publishFileMsgStatus));
}
```

### Response

```csharp
{
    "Timetoken":15957738720237858
}
```

### Returns

Returns `PNResult<PNPublishFileMessageResult>`.

| Property Name | Type | Description |
| --- | --- | --- |
| `Result` | PNPublishFileMessageResult | Returns a `PNPublishFileMessageResult` object. |
| `Status` | PNStatus | Returns a `PNStatus` object. |

`PNPublishFileMessageResult` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `Timetoken` | long | Returns a long representation of the timetoken when the `message` was published. |