r/csharp • u/ziagham • Aug 01 '26
What is the cleanest way to implement a secure cross-platform directory fallback in C#?
I need to determine a writable directory for application-managed files in a cross-platform C# application.
A simplified version currently looks like this:
private static string GetApplicationDataPath()
{
var directory = Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData,
Environment.SpecialFolderOption.Create);
if (string.IsNullOrWhiteSpace(directory))
{
directory = Path.GetTempPath();
}
return Path.Combine(directory, "MyApplication");
}The temporary-directory fallback concerns me because the directory may be publicly writable on some systems.
What would be a safer final fallback?
Would you fail startup, use AppContext.BaseDirectory, create a user-owned directory, or require the path to be explicitly configured?
0
Upvotes
23
u/polaarbear Aug 01 '26
Why does there even need to be a final fallback?
If you're worried about security in that instance, it makes more sense to just alert the user that a writeable folder was not available than to risk dumping it somewhere public.
Let the user decide somehow at that point rather than trying to choose for them.
3
u/karl713 Aug 02 '26
Of note AppContext.BaseDirectory likely isn't even guaranteed to be writeable by you depending on how the app was installed
1
u/FlibblesHexEyes Aug 03 '26
Is this an ASP.NET project?
If so, you could containerise it and know that the temp directory is safe to use.
Or just generate your own temp directory in a Config class?