如何获取 Windows 和 Linux 中的根目录?

How to get the root dir in Windows and Linux?

我使用 .net6 编写了一个小软件,它应该在 Windows 和 Linux (Ubuntu) 上 运行。在这个软件中,我需要访问文件夹中的文件。 Linux: /folder1/folder2/file.txt Windows: d:\folder1\folder2\file.txt 两个系统上的文件夹结构和文件名相同。 此代码目前有效

string[] pfad;
pfad = new[] { "folder1", "folder2","file.txt" };
Console.WriteLine(System.IO.Path.Combine(pfad));

并在 Linux 和 Windows 下提供正确的文件夹结构。

如何定义根目录? / 在 Linux 和 d:\ 在 Windows 我能以某种方式检测到 OS 类型吗?或者最好的方法是什么?

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);在 Windows 下“修复”到 C:... - 我想使用另一个驱动器。

您可以像这样使用System.Runtime.InteropServices.RuntimeInformation

        string rootPath;  

        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            rootPath = @"d:\";
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            rootPath = "/";
        }

借用 stefan 的答案,但使用 OperatingSystem class 而不是 RuntimeInformation(因为 OperatingSystemSystem 的一部分,我相信它是更可取)

string rootPath;

if (OperatingSystem.IsWindows())
    rootPath = @"d:\";
else if (OperatingSystem.IsLinux())
    rootPath = "/";
else
{
    // maybe throw an exception
}