列出网络位置的所有共享文件夹

Cor*_*elC 5 .net c# networking shared unc

我想列出网络服务器中的所有共享目录.

列出我使用的共享网络目录中的目录

Directory.GetDirectories(@"\\server\share\")
Run Code Online (Sandbox Code Playgroud)

问题是我要列出所有文件夹\\server.

如果我使用相同的方法,我会得到一个例外

UNC路径的格式应为\ server\share

我到处寻找,我找不到解决方案.

有没有人知道我应该做什么才能显示文件夹\\share

Sel*_*rio 2

我能找到的最佳解决方案是从隐藏的 cmd.exe 实例调用“net”应用程序:

public static string[] GetDirectoriesInNetworkLocation(string networkLocationRootPath)
{
    Process cmd = new Process();
    cmd.StartInfo.FileName = "cmd.exe";
    cmd.StartInfo.RedirectStandardInput = true;
    cmd.StartInfo.RedirectStandardOutput = true;
    cmd.StartInfo.CreateNoWindow = true;
    cmd.StartInfo.UseShellExecute = false;
    cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    cmd.Start();
    cmd.StandardInput.WriteLine($"net view {networkLocationRootPath}");
    cmd.StandardInput.Flush();
    cmd.StandardInput.Close();

    string output = cmd.StandardOutput.ReadToEnd();

    cmd.WaitForExit();
    cmd.Close();

    output = output.Substring(output.LastIndexOf('-') + 2);
    output = output.Substring(0, output.IndexOf("The command completed successfully."));

    return
        output
            .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(x => System.IO.Path.Combine(networkLocationRootPath, x.Substring(0, x.IndexOf(' '))))
            .ToArray();
}
Run Code Online (Sandbox Code Playgroud)

根据您的使用案例,您可能需要验证 networkLocationRootPath 以避免任何 cmd 注入问题。