UE5 C++ 删除文件

创建 C++ 蓝图函数库

如果项目是蓝图项目,需要先启用 C++ 支持(通过 "File > New C++ Class" 创建任意类,引擎会自动配置 C++ 环境)。

创建蓝图函数库

  • 在 Content Browser 中右键 → "C++ Classes" → 选择你的项目 → 右键 → "New C++ Class"
  • 父类选择 "Blueprint Function Library",命名为 "FileOperationLibrary"

编写代码

.h头文件代码:

cpp 复制代码
#pragma once

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "FileOperationLibrary.generated.h"

/**
 *
 */
UCLASS()
class YourProject_API UFileOperationLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()

public:

	// 增强版头文件
	UFUNCTION(BlueprintCallable, Category = "File Management", meta = (DisplayName = "Delete File Safely", ToolTip = "Delete File Safely"))
		static bool DeleteFileSafely(const FString& FilePath, bool bShowNotification = true);
};

.cpp文件代码

cpp 复制代码
#include "FileOperationLibrary.h"
#include "HAL/PlatformFileManager.h"

// 增强版实现
bool UFileOperationLibrary::DeleteFileSafely(const FString& FilePath, bool bShowNotification)
{
	IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();

	if (!PlatformFile.FileExists(*FilePath))
	{
		if (bShowNotification)
		{
			UE_LOG(LogTemp, Warning, TEXT("File does not exist: %s"), *FilePath);
		}
		return false;
	}

	bool bSuccess = PlatformFile.DeleteFile(*FilePath);

	if (bShowNotification)
	{
		if (bSuccess)
		{
			UE_LOG(LogTemp, Log, TEXT("Successfully deleted file: %s"), *FilePath);
		}
		else
		{
			UE_LOG(LogTemp, Error, TEXT("Failed to delete file: %s"), *FilePath);
		}
	}

	return bSuccess;
}

编译代码:点击 UE 工具栏的 "Compile" 按钮编译 C++ 代码。

在蓝图中使用刚创建的节点

正常传入文件路径就行。

如"C:/MyProject/Saves/OldSave.sav"