---
source_url: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/files
title: File Sharing API for C# SDK
updated_at: 2026-05-18T12:49:22.054Z
sdk_name: PubNub C# SDK
sdk_version: 8.2.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 C# SDK

PubNub C# SDK, use the latest version: 8.2.0

Install:

```bash
dotnet add package PubNub@8.2.0
```

Allows users to upload and share files. You can upload any file of up to 5 MB in size. This feature is commonly used in social apps to share images, or in medical apps to share medical records for patients.

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`.

:::tip Request execution
Use `try`/`catch` when working with the C# SDK.
If a request has invalid parameters (for example, a missing required field), the SDK throws an exception. If the request reaches the server but fails (server error or network issue), the error details are available in the returned `status`.
```csharp
try
{
    PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
        .Message("Why do Java developers wear glasses? Because they can't C#.")
        .Channel("my_channel")
        .ExecuteAsync();
    PNStatus status = publishResponse.Status;
    Console.WriteLine("Server status code : " + status.StatusCode.ToString());
}
catch (Exception ex)
{
    Console.WriteLine($"Request can't be executed due to error: {ex.Message}");
}
```
:::

## 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.

### Method(s)

```csharp
pubnub.SendFile()
        .Channel(string)
        .File(string|byte[])
        .FileName(string)
        .Message(string)
        .ShouldStore(bool)
        .Meta(Dictionary<string, object>)
        .Ttl(int)
        .CustomMessageType(string)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| Channel | string | Yes |  | `Channel` for the file. |
| File | string | Yes |  | Full path of the file with file name or an array of bytes. When using an array of bytes, you must set `FileName`. |
| FileName | string | Optional |  | Name of the file to send. You can use it to override the default file name. |
| Message | string | Optional |  | Message which should be sent along with file to specified `channel`. |
| ShouldStore | bool | Optional |  | Whether PubNub published file `message` should be stored in `channel` history. |
| Meta | Dictionary<string, | Optional |  | Dictionary`<string, object>` with values which should be used by PubNub service to filter file messages. |
| TtL | int | Optional |  | How long message should be stored in channel's storage. |
| 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`. |

:::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/c-sharp/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;

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

Pubnub pubnub = new Pubnub(pnConfiguration);
try
{
    PNResult<PNFileUploadResult> fileUploadResponse = await pubnub.SendFile()
        .Channel("my_channel")
        .File("path/to/your/file/cat_picture.jpg")
        .Message("Look at this photo!")
        .CustomMessageType("file-message")
        .ExecuteAsync();

    PNFileUploadResult fileUploadResult = fileUploadResponse.Result;
    PNStatus fileUploadStatus = fileUploadResponse.Status;

    if (!fileUploadStatus.Error && fileUploadResult != null)
    {
        Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadResult));
    }
    else
    {
        Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileUploadStatus));
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Request cannot be executed due to error: {ex.Message}");
}
```

### 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 list of files uploaded to `Channel`.

### Method(s)

```csharp
pubnub.ListFiles()
        .Channel(string)
```

| 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. |

### Sample code

```csharp
using PubnubApi;

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

Pubnub pubnub = new Pubnub(pnConfiguration);
PNResult<PNListFilesResult> listFilesResponse = await pubnub.ListFiles()
    .Channel("my_channel")
    .ExecuteAsync();
PNListFilesResult listFilesResult = listFilesResponse.Result;
PNStatus listFilesStatus = listFilesResponse.Status;
if (!listFilesStatus.Error && listFilesResult != null)
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(listFilesResult));
}
else
{
    Console.WriteLine(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

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

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

`PNListFilesResult` contains the following properties:

| 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` contains the following properties:

| 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 URL which can be used to download file from target `Channel`.

### Method(s)

```csharp
pubnub.GetFileUrl()
        .Channel(string)
        .FileId(string)
        .FileName(string)
```

| 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`. |

### Sample code

```csharp
using PubnubApi;

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

Pubnub pubnub = new Pubnub(pnConfiguration);
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)
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlResult));
}
else
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(getFileUrlStatus));
}
```

### Response

```csharp
{
    "Url":"http://ps.pndsn.com/v1/files/demo/channels/my_channel/files/d9515cb7-48a7-41a4-9284-f4bf331bc770/cat_picture.jpg?pnsdk=NET461CSharp4.9.0.0&timestamp=1595771548&uuid=pn-9ce9e988-8e04-40bf-90c4-ebe170478f7d"
}
```

### Returns

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

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

`PNFileUrlResult` contains the following properties:

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

## Download file

Download file from specified `Channel`.

### Method(s)

```csharp
pubnub.DownloadFile()
        .Channel(string)
        .FileId(string)
        .FileName(string)
```

| 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`. |

:::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/c-sharp/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;

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

Pubnub pubnub = new Pubnub(pnConfiguration);
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
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(fileDownloadResult.FileName));
}
else
{
    Console.WriteLine(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

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

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

`PNDownloadFileResult` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `FileBytes` | byte[] | byte array of the downloaded file. Use SaveFileToLocal method to copy file to local. |
| `FileName` | string | Name of the downloaded file from channel. |
| `SaveFileToLocal(string)` |  | Provide full destination path to `SaveFileToLocal` for saving the downloaded file locally. |

## Delete file

Delete file from specified `Channel`.

### Method(s)

```csharp
pubnub.DeleteFile()
        .Channel(string)
        .FileId(string)
        .FileName(string)
```

| 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`. |

### Sample code

```csharp
using PubnubApi;

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

Pubnub pubnub = new Pubnub(pnConfiguration);
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)
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(deleteFileResult));
}
else
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(deleteFileStatus));
}
```

### Response

```csharp
{}
```

### Returns

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

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

`PNDeleteFileResult` returns empty object

## 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)
```

| 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 | Meta data object which can be used with the filtering ability. |
| `ShouldStore`Type: boolDefault: `true` | Store 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`. |

### Sample code

```csharp
using PubnubApi;

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

Pubnub pubnub = new Pubnub(pnConfiguration);
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)
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(publishFileMsgResult));
}
else
{
    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(publishFileMsgStatus));
}
```

### Response

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

### Returns

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

| 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. |