---
source_url: https://www.pubnub.com/docs/data-storage/files/list-and-manage-stored-files
title: List and manage stored files
updated_at: 2026-09-30T07:20:08.000Z
---

# List and manage stored files

## Documentation index

To discover more PubNub resources:

1. Fetch [PubNub's llms.txt](https://www.pubnub.com/llms-full.txt) for a list of available pages in Markdown format.
2. Identify relevant URLs from that index.
3. Fetch the target pages.

Do not assume a path exists, always check the index first.

This guide shows you how to list files uploaded to a channel and delete a file by its ID.

The examples on this page are written for the current SDK releases: C# 9.0.0, Dart 8.0.3, Go v10.0.0, Java 6.4.5, JavaScript 13.0.3, Kotlin 13.4.4, Objective-C 7.0.4, Python 10.7.2, and Swift 10.2.0. Each example assumes a PubNub client initialized for its SDK, unless the example sets one up itself.

**Prerequisites:**

* File Sharing must be enabled on your keyset in the [Admin Portal](https://admin.pubnub.com).
* If [Access Manager](https://www.pubnub.com/docs/security/access-control/overview.md) is enabled, the token must grant `read` on the channel to list files and `delete` to remove them.

## List files

A single list-files call returns up to 100 files for a channel. The response includes the file name, ID, size, and created timestamp for each file.

### JavaScript

```javascript
const result = await pubnub.listFiles({ channel: 'my_channel' });
```

### C#

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

### Go

```go
resListFile, statusListFile, errListFile := pn.ListFiles().
  Channel("my_channel").Execute()
fmt.Println(resListFile, statusListFile, errListFile)
if resListFile != nil {
    for _, m := range resListFile.Data {
        fmt.Println(m.ID, m.Created, m.Name, m.Size)
    }
}
```

### Objective-C

```objectivec
PNListFilesRequest *request = [PNListFilesRequest requestWithChannel:@"my_channel"];
request.limit = 100;
request.next = ...;

[self.client listFilesWithRequest:request
                       completion:^(PNListFilesResult *result, PNErrorStatus *status) {
    if (!status.isError) {
        /**
         * Uploaded files list successfully fetched.
         *   result.data.files - List of uploaded files (information).
         *   result.data.next - 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.
         *   result.data.count - Total number of files uploaded to channel.
         */
    } else {
        /**
         * Handle fetch files list error. Check 'category' property to find out
         * possible issue because of which request failed.
         *
         * Request can be resent using: [status retry]
         */
    }
}];
```

### Java

```java
pubnub.listFiles()
        .channel("my_channel")
        .async(result -> {
            result.onSuccess(res -> {
                    System.out.println("files status: " + res.getStatus());
                    System.out.println("files status: " + res.getNext());
                    System.out.println("files status: " + res.getCount());
                    System.out.println("files status: " + res.getCount());
                    for (PNUploadedFile file : res.getData()) {
                        System.out.println("files fileId: " + file.getId());
                        System.out.println("files fileName: " + file.getName());
                        System.out.println("files fileSize: " + file.getSize());
                        System.out.println("files fileCreated: " + file.getCreated());
                    }
            }).onFailure(exception -> {
                exception.printStackTrace();
            });
        });
```

### Python

```python
# synchronous
pubnub.list_files().channel("my_channel").sync()

# multithreaded asynchronous
def callback(result, status):
    if status.is_error():
        print(f"Request failed: {status.error_data}")
        return
    print(result)

pubnub.list_files().channel("my_channel").pn_async(callback)
```

### Swift

```swift
// Retrieve list of files uploaded to a channel
pubnub.listFiles(channel: "my_channel") { result in
  switch result {
  case let .success(response):
    print("There are \(response.files.count) file(s) found")
    print("The next page used for pagination: \(String(describing: response.next))")
  case let .failure(error):
    print("An error occurred while fetching the file list: \(error.localizedDescription)")
  }
}
```

### Dart

```dart
import 'package:pubnub/pubnub.dart';

void main() async {
  var pubnub = PubNub(
    defaultKeyset: Keyset(
      subscribeKey: 'sub-c-abc-123',  // Replace with your subscribe key
      publishKey: 'pub-c-def-456'     // Replace with your publish key
    ),
  );

  try {
    var files = await pubnub.files.listFiles('my_channel');

    print('Number of files uploaded: ${files.count}');
    for (var file in files.filesDetail) {
      print('File name: ${file.name}, ID: ${file.id}, Size: ${file.size}, Created: ${file.created}');
    }
  } catch (e) {
    print('Failed to list files: $e');
  }
}
```

If more than 100 files exist on the channel, the response includes a `more` cursor. Pass it as `next` in a subsequent call to fetch the next page of results.

## Delete a file

To delete a file, you need the file ID and file name returned by `listFiles` or from the original upload response.

### JavaScript

```javascript
try {
  const deleteFileResponse = await pubnub.deleteFile({
    channel: 'my_channel',
    id: '...',
    name: 'cat_picture.jpg',
  });
  console.log('File deleted successfully:', deleteFileResponse);
} catch (error) {
  console.error(`Error deleting file: ${error}`);
}
```

### C#

```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));
}
```

### Go

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"os"

	pubnub "github.com/pubnub/go/v10"
)

// Example_deleteFile demonstrates deleting a file from a channel
func Example_deleteFile() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	pn := pubnub.NewPubNub(config)

	// Delete a specific file
	// You would get these values from your file upload response or ListFiles
	fileID := uploadResp.Data.ID // Replace uploadResp.Data.ID with your file ID
	fileName := "to-delete.txt"  // Replace with your file name

	_, status, err := pn.DeleteFile().
		Channel("files-channel").
		ID(fileID).     // File ID from upload or list response
		Name(fileName). // File name
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Println("File deleted successfully")
	}

	// Output:
	// File deleted successfully
}
```

### Objective-C

```objectivec
PNDeleteFileRequest *request = [PNDeleteFileRequest requestWithChannel:@"channel"
                                                            identifier:@"<file-identifier>"
                                                                  name:@"greetings.txt"];

[self.client deleteFileWithRequest:request completion:^(PNAcknowledgmentStatus *status) {
    if (!status.isError) {
        // File successfully has been deleted.
    } else {
        /**
         * Handle file delete error. Check 'category' property to find out possible issue
         * because of which request did fail.
         *
         * Request can be resent using: [status retry]
         */
    }
}];
```

### Java

```java
pubNub.deleteFile()
        .channel("my_channel")
        .fileName("cat_picture.jpg")
        .fileId("d9515cb7-48a7-41a4-9284-f4bf331bc770")
        .async(result -> { /* check result */ });
```

### Kotlin

```kotlin
pubnub.deleteFile(
    channel = "my_channel",
    fileName = "cat_picture.jpg",
    fileId = "someFileId"
).async { result ->
    result.onFailure { exception ->
        // Handle error
    }.onSuccess { value ->
        // Handle successful method result
    }
}
```

### Python

```python
pubnub.delete_file(
    channel="ch1",
    file_id=file_data['id'],
    file_name=file_data['name']
).sync()

print("File deleted")
```

### Swift

```swift
// Remove a File from a channel
pubnub.remove(
  fileId: "id-of-a-file",
  filename: "example.png",
  channel: "my_channel"
) { result in
  switch result {
  case let .success(response):
    print("The file whose ID is \(response.fileId) was removed from \(response.channel)")
  case let .failure(error):
    print("An error occurred while removing the file: \(error.localizedDescription)")
  }
}
```

### Dart

```dart
await pubnub.files.deleteFile(
  'my_channel', 'someFileID', 'cat_picture.jpg');
```

Deleting a file removes it from File Sharing storage. It does not remove the file event from [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md) history. If Message Persistence is enabled, the file event record remains in history after the file is deleted.

## Related tasks

* [Send a file to a channel](https://www.pubnub.com/docs/data-storage/files/send-file-to-channel.md). Upload a file and get back the file ID used for deletion.
* [Receive and download files](https://www.pubnub.com/docs/data-storage/files/receive-and-download-files.md). Handle the file event on the subscriber side.

Last updated at: 2026-09-30T07:20:08.000Z
