CodeDom编译错误(路径上的非法字符)

时间:2015-01-12 05:15:53

标签: c# codedom

我正在尝试使用C#应用程序创建一个单独的.exe,似乎我遇到了错误。

使用下面的代码,我收到此错误:

System.ArgumentException: Illegal characters in path.
   at System.IO.Path.GetFileName(String path)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.OpenRead(String path)
   at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, String[] fileNames)
   at Program_Name.Core.BuildStub(String FileName, String mutex) in c:\Users\Tom\Documents\Visual Studio 2013\Projects\Program_Name\Program_Name\Core.cs:line 45
   at Program_Name.Builder.button1_Click(Object sender, EventArgs e) in c:\Users\Tom\Documents\Visual Studio 2013\Projects\Program_Name\Program_Name\Builder.cs:line 30

这是什么原因?我正在使用msdn.microsoft.com上的代码(链接:http://msdn.microsoft.com/en-us/library/saf5ce06(v=vs.110).aspx

我的代码如下:

public static void BuildStub(string FileName, string mutex)
{
    CSharpCodeProvider provider = new CSharpCodeProvider();
    CompilerParameters cp = new CompilerParameters();

    cp.ReferencedAssemblies.Add("System.dll");

    cp.GenerateExecutable = true;

    cp.OutputAssembly = "name.exe";

    cp.GenerateInMemory = false;
    string sourceFile = Properties.Resources.SourceCode;

    CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);

    if (cr.Errors.Count > 0)
    {
        Console.WriteLine("Errors building {0} into {1}",
                sourceFile, cr.PathToAssembly);
        foreach (CompilerError ce in cr.Errors)
        {
            Console.WriteLine("{0}", ce.ToString());
            Console.WriteLine();
        }
    }
    else
    {
        Console.WriteLine("Source {0} built into {1} successfully.",
            sourceFile, cr.PathToAssembly);
    }

    // Return the results of compilation. 
    if (cr.Errors.Count > 0)
        Console.WriteLine("There were errors RIP");
}

我正在尝试构建的代码(Properties.Resources.SourceCode)是:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:1)

CompileAssemblyFromFile()期望第二个参数为文件名,您想要的是CompileAssemblyFromSource()