FivePD API

Loading Custom Files

To load custom configuration or data files, we recommend using the IAddonFileHandlerService. This service ensures that you can reliably access your files regardless of the addon's installation path.

How It Works

  1. Register Files: First, you must list all custom files you intend to load in the Files array of your metadata.yaml file. The service cannot access any file that is not listed here.
  2. Inject the Service: Inject the IAddonFileHandlerService into your class constructor.
  3. Load Files: Use one of the service's methods to load your file's content.

Loading Methods

The service provides two primary methods for loading files:

  • LoadFile<T>(string path): This generic method automatically deserializes a YAML or JSON file into an instance of a specified C# class (T). This is useful for structured configuration. If the file does not exist or contains malformed content, this method returns the default value for the specified type (T).
  • LoadFile(string path): This method reads the entire content of any specified file and returns it as a string. This is useful for unstructured data or file types other than YAML/JSON.

For more details, see the IAddonFileHandlerService documentation.

Example

Here is a complete example of how to load a config.yaml file and map it to a C# class.

metadata.yaml
FriendlyName: My Awesome Addon
Version: 100
FriendlyVersion: 1.0.0
Author: Your Name
Assemblies:
  - MyAwesomeAddon.dll
Files: 
  - config.yaml
A: 123
B: true
C:
  - item 1
  - item 2
  - item 3
using System.Collections.Generic;

namespace MyAwesomeAddon;

public class Config
{
    public int A { get; set; }
    public bool B { get; set; } 
    public List<string> C { get; set; }
}
using System.Collections.Generic;
using System.Threading.Tasks;
using CitizenFX.Core;
using FivePD.Server.API;
using FivePD.Server.Interfaces;
using FivePD.Server.Interfaces.Addons;

namespace MyAwesomeAddon;

public class MyAwesomeExtension : IExtension
{
    private readonly Config _config; 

    public MyAwesomeExtension(IAddonFileHandlerService fileHandlerService) 
    {
        _config = fileHandlerService.LoadFile<Config>("config.yaml"); 
    }

    public Task OnStarted()
    {
        Debug.WriteLine($"Config A: {_config.A}"); 
        Debug.WriteLine($"Config B: {_config.B}"); 
        Debug.WriteLine("Config C items:"); 
        foreach (var item in _config.C) 
        { 
            Debug.WriteLine(item); 
        } 

        return Task.CompletedTask;
    }

    public Task OnStopped()
    {
        return Task.CompletedTask;
    }
}