keywords: UE4, File & Directory Operation Notes

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

Save byte array:

TArray<uint8> Stream;
Stream.Add(1);
FFileHelper::SaveArrayToFile(Stream, *FilePath);
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 get directory of custom config file? (SaveStringToFile on android failed)

FPaths::ProjectDir() works on Windows, but would fail on 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 get Screenshots directory
//e.g. [Project]/Saved/Screenshots/Windows/
GetDefault<UEngine>()->GameScreenshotSaveDirectory.Path

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