所以我正在制作一个WPF应用程序,使用CSharpCodeProvider编译存储在字符串中的代码。除了一部分外,其他一切都很好。当我尝试使用Process.Start((时,它会给我"找不到元数据文件System.Diagnostics.dll"错误。我不知道这意味着什么。
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Dynamically_compile_codes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", txtFrameWork.Text } });
Button button = (Button)sender;
CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll","System.Core.dll","System.Diagnostics.dll"}, txtOutput.Text,true);
//generate exe, not dll
parameters.GenerateExecutable = true;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, textBox.Text);
if (results.Errors.HasErrors)
{
results.Errors.Cast<CompilerError>().ToList().ForEach(error=> txtStatus.Text+=error.ErrorText+"/r/n");
}
else
{
//If we clicked run then launch our EXE
Process.Start(txtOutput.Text);
}
}
}
}
这是存储在字符串中的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Hidden_Console_Application
{
class Program
{
static void Main(string[] args)
{
Process.Start("explorer.exe");
}
}
}
System.Diagnostics是位于System.dll程序集中的命名空间。CompilerParameters构造函数需要程序集名称的字符串集合,因此正在查找名为System.Diagnostics的已加载程序集,但该程序集不存在。
应为:
CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll","System.Core.dll","System.dll"}, txtOutput.Text,true);