尝试从 cmd 编译时找不到元数据文件

Metadata file could not be found when trying to compile from the cmd

这是我的示例:

using System;
using Windows.Networking.Vpn;
static void main()
{VpnManagementAgent mgr = new VpnManagementAgent();
 VpnNativeProfile profile = new VpnNativeProfile() { AlwaysOn = false,
    NativeProtocolType = VpnNativeProtocolType.L2tp,
    ProfileName = "MyConnection",
    RememberCredentials = true, RequireVpnClientAppUI = true,
    RoutingPolicyType = VpnRoutingPolicyType.SplitRouting,
    TunnelAuthenticationMethod = VpnAuthenticationMethod.PresharedKey,
    UserAuthenticationMethod = VpnAuthenticationMethod.Mschapv2, }; 
    profile.Servers.Add("vpn.example.com"); 
    VpnManagementErrorStatus profileStatus = await mgr.AddProfileFromObjectAsync(profile);
    Console.WriteLine($"{profileStatus}\n");  }

这是我尝试编译的方式(来自 VS 2019 的开发人员命令提示符):

csc program.cs /r:Windows.Networking.Vpn.dll

这是我安装的工具包的屏幕截图:

这是我的输出:

Microsoft (R) Visual C# Compiler version 3.100.119.28106 (58a4b1e7)
Copyright (C) Microsoft Corporation. All rights reserved.

error CS0006: Metadata file 'Windows.Networking.Vpn.dll' could not be found

这是来自 msdn 的 link:

Assemblies:Windows.Networking.Vpn.dll, Windows.dll

您的代码不正确。 visual studio 中的 Windows.Networking.Vpn namespace is for UWP applications, and in your code you attempt to use the System.Console.WriteLine() function, which is invalid in this context. Even though the only error csc.exe is throwing is the file not being found, that is not your problem. try making a new UWP 应用程序并在 visual studio 中编译它,因为这使它变得更加容易。

您要查找的类型在 Windows 运行时元数据文件中定义并以本机代码实现。您需要参考 winmd 的。有一些快捷方式(例如引用使用 OS 安装的元数据),但这会使您的项目变得脆弱。通常,您需要引用已安装的 SDK 版本。您可以使用 VS 命令提示符中的路径变量来提供一些帮助,例如(使用 17763 SDK):

csc Program.cs \
-reference:"%WindowsSdkDir%\References\%WindowsSdkVersion%\Windows.Foundation.FoundationContract.0.0.0\Windows.Foundation.FoundationContract.winmd" \
-reference:"%WindowsSdkDir%\References\%WindowsSdkVersion%\Windows.Foundation.UniversalApiContract.0.0.0\Windows.Foundation.UniversalApiContract.winmd"

然而,这仍然会有一些脆弱性,因为这些路径中的合约​​版本号会随着 SDK 的升级而改变。 VS项目系统从“%WindowsSdkDir%\Platforms\UAP\%WindowsSdkVersion%\Platform.xml”或“%WindowsSdkDir%\Platforms\UAP\%WindowsSdkVersion%\PreviousPlatforms.xml" 以获得目标操作系统版本的正确 API 信息。