keywords: UE4 File Directory Operation Notes, Operation System, Platform Process, Windows API, Native Interface

How to read file?

Read string:

FString Str;
FFileHelper::LoadFileToString(Str, FilePath);

Read string list:

TArray<FString> StrList;
FFileHelper::LoadFileToStringArray(StrList, FilePath);

Read byte array:

TArray<uint8> Stream;
FFileHelper::LoadFileToArray(Stream, *FilePath);
How to save file?

Save string:

TArray<uint8> Stream;
Stream.Add(1);
FFileHelper::SaveStringToFile(FBase64::Encode(Stream), *FilePath, FFileHelper::EEncodingOptions::ForceUTF8);

Save byte array:

TArray<uint8> Stream;
Stream.Add(1);
FFileHelper::SaveArrayToFile(Stream, *FilePath);
How to create directory or check directory if exists?
FString SavePath = FPaths::ProjectSavedDir() + TEXT("/TestDir/");
IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
if (!PlatformFile.DirectoryExists(*SavePath))
{
    PlatformFile.CreateDirectory(*SavePath);
}
How to get absolute path of project
FString AbsDir = UKismetSystemLibrary::GetProjectDirectory();

Or:

FString RelativePath = FPaths::ProjectDir();
FString AbsDir = UKismetSystemLibrary::ConvertToAbsolutePath(RelativePath);
File path format using data time
FDateTime Time = FDateTime::Now();
int Year = Time.GetYear();
int Month = Time.GetMonth();
int Day = Time.GetDay();
int Hour = Time.GetHour();
int Minute = Time.GetMinute();
int Second = Time.GetSecond();
FString SavePath = FPaths::ProjectSavedDir() + TEXT("/TestDir/");
FString Filename = FString::Printf(TEXT("TestFile_%d-%.2d-%.2d-%.2d%.2d%.2d.txt"), Year, Month, Day, Hour, Minute, Second);
FString FilePath = SavePath + Filename;
FFileHelper::SaveStringToFile(Content, *FilePath, FFileHelper::EEncodingOptions::ForceUTF8);
How to find the latest modified file in directory?
TMap<int32, FString> FileMap;
TArray<int32> TimeArray;
TArray<FString> FoundFiles;
FString Directory = GetDefault<UEngine>()->GameScreenshotSaveDirectory.Path;
FString fileExt = TEXT("png");
IFileManager::Get().FindFiles(FoundFiles, *Directory, *fileExt);

for(FString FileName : FoundFiles)
{
    FDateTime Data = IFileManager::Get().GetTimeStamp(*FileName);
    int32 UnixTimestamp = Data.GetSecond();
    FileMap.Add(UnixTimestamp, FileName);
    TimeArray.Add(UnixTimestamp);
}
TimeArray.Sort();
if(TimeArray.Num() > 0)
{
    FString* LatestFile = FileMap.Find(TimeArray[0]);
    UE_LOG(LogTemp, Log, TEXT("latestfile: %s"), *LatestFile);
}
How to create sub-directory (full path, multiple folder) recursively
//BaseDir: D:/MyGame/Content/
//FullDir: D:/MyGame/Content/foo/bar/baz/
void ARGPcgConvertActor::CreateSubDirectory(const FString& BaseDir, const FString& FullDir)
{
    FString BaseDirNew = BaseDir.Replace(TEXT("//"), TEXT("/"));
    FString FullDirNew = FullDir.Replace(TEXT("//"), TEXT("/"));
    FString RelativeDir = FullDirNew.Replace(*BaseDirNew, TEXT(""));

    //remove the first slash in beginning
    if (RelativeDir.Left(1) == TEXT("/"))
    {
        RelativeDir = RelativeDir.Right(RelativeDir.Len() - 1);
    }

    FString LastRelativeDir = BaseDir;
    while (RelativeDir.Len() > 0)
    {
        FString SubDir;
        int32 SlashIndex = RelativeDir.Find("/");
        if (SlashIndex >= 0)
        {
            SubDir = RelativeDir.Mid(0, SlashIndex);
            RelativeDir = RelativeDir.Mid(SlashIndex + 1, RelativeDir.Len() - SlashIndex);
        }
        else
        {
            SubDir = RelativeDir;
            RelativeDir = TEXT("");
        }
        
        FString NewDir = FPaths::Combine(LastRelativeDir, SubDir);
        IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
        if (!PlatformFile.DirectoryExists(*NewDir))
        {
            PlatformFile.CreateDirectory(*NewDir);
        }
        LastRelativeDir = NewDir;
    }
}
How to get directory of custom config file? (SaveStringToFile in android failed)

FPaths::ProjectDir() works in Windows, but will fail in Android.
Solution:

FPlatformMisc::GamePersistentDownloadDir()

Or:

FString SaveDirectory;

#if PLATFORM_WINDOWS
    SaveDirectory = FWindowsPlatformMisc::GamePersistentDownloadDir();
#endif

#if PLATFORM_ANDROID
    SaveDirectory = FAndroidMisc::GamePersistentDownloadDir();
#endif

#if PLATFORM_IOS
    SaveDirectory = FIOSPlatformMisc::GamePersistentDownloadDir();
#endif

Origin:
Shipping build won’t create .ini file in GameDir()
https://forums.unrealengine.com/t/shipping-build-wont-create-ini-file-in-gamedir/99905

How to execute OS command (Windows batch, cmd) in C++
FString ExePath = TEXT("C:/Program Files/WinRAR/Rar.exe");
FString Args = TEXT("a -df -k -r -s D:/mysqldump/%filename%-%data_time_str%.rar  %filename%-%date_str%*.sql");
FProcHandle Handle = FPlatformProcess::CreateProc(*ExePath, *Args, false, true, false, nullptr, 0, nullptr, nullptr);

//wait process while running native command
FPlatformProcess::WaitForProc(Handle);

//check if process was finished
FPlatformProcess::IsProcRunning(Handle);
How to get Conent directory
//e.g. [Project]/Content/
FString ContentDir = FPaths::ProjectContentDir();

FPaths::ProjectContentDir() also works for package building.

How to get Config (ini file) directory
//[Project]/Config/WindowsNoEditor/
FPaths::ProjectConfigDir()
FPaths::SourceConfigDir()

//[Project]/Saved/Config/WindowsNoEditor/
FPaths::GeneratedConfigDir()

example:

[MyGameSettings]
+AssetList=/Script/Engine.Blueprint'/Game/Test/MyActor01.MyActor01'
+AssetList=/Script/Engine.Blueprint'/Game/Test/MyActor02.MyActor02'
+AssetList=/Script/Engine.Blueprint'/Game/Test/MyActor03.MyActor03'
TArray<FString> AssetList;
FString Path = FPaths::GeneratedConfigDir() + TEXT("DefaultMyGameSettings.ini");
GConfig->GetArray(TEXT("/Script/MyGame.MyGameSettings"), TEXT("+AssetList"), AssetList, Path);
How to write Config (ini file)

See: [UE4]UObject Notes

How to get project name
FApp::GetProjectName()
How to get Screenshots directory
//e.g. [Project]/Saved/Screenshots/WindowsNoEditor/
GetDefault<UEngine>()->GameScreenshotSaveDirectory.Path
How to get file size
IPlatformFile& Handle = FPlatformFileManager::Get().GetPlatformFile();
int64 Size = Handle.FileSize(TEXT("C:/test.png"));
How to generate MD5 for files
FMD5Hash Hash = FMD5Hash::HashFile(Filename);
const FString HasAsString = LexToString(Hash);

Generate MD5 for string:

FString MD5Str = FMD5::HashAnsiString(TEXT("Wang Aiguo"));

Generate MD5 for byte array:

static FString HashBytes(const uint8* input, uint64 inputLen)

Origin:
https://forums.unrealengine.com/t/md5-hex-string-from-file/131321


There are too many unknowns and impossibility in the world. Think of all this is about to face, My Heart Goes Boom.