I have a strange requirement, I have been asked to code a certain validation script in VBScript because its in plain text. But I am more comfortable in c#. So is there anyway to schedule it in Task Scheduler such that the compiler will compile the program(source code in .cs file) and run it on the fly.

有帮助吗?

解决方案 3

Assuming you want behavior similar to VBScript/JavaScript in command line where they behave similar to normal EXE files. To see how JS/VBS are executed check output of assoc .js and ftype JSType commands.

Basically you want to create CMD/BAT file that will launch CSC to compile you .cs file and than run executable with all original parameters of CMD file. Than associate this new CMD file with .CS file type. To configure associations check ftype /? provides plenty of info.

Note that it may be good idea to have custom extension instead of default .cs (i.e. .cssript) to avoid confusion with regular .cs files.

其他提示

This is really easy to do as a single self-compiling CMD batch file. This one is pure text and runnable (from my blog entry - Dynamically Create an Executable from user-data Text).

You can call this text file directly as a batch file and it will run as an EXE. Simply save the file with a .CMD extension (including all the C# code) and run it as normal.

/* This section is run in batch file mode
%FrameworkDir%%FrameworkVersion%\csc.exe /nologo /out:bootstrap.exe /Reference:%FrameworkDir%%FrameworkVersion%\System.Net.dll "%0"
goto end
*/

using System;

static class Program
{
    static void Main(string[] argv)
    {
        if (argv.Length > 0)
            Console.Write(argv[0]);
        Console.WriteLine();
    }
}
/*
:end

REM ** Run the program
BootStrap.exe "Hello world!"
REM */

The /* */ comments allow you to put the batch file commands to compile itself and of course they're ignored by the C# compiler. Batch (CMD) files will skip over an errors to the next line, so this file runs like an EXE exept that it's text. As a refinement, you might want to change the /out target to somewhere in %TEMP%.

[Updated] Simpler Hello World sample.

What you are looking for is the CSharpCodeProvider.

This allows you to compile or evaluate C# code from a source and run it. It can do it on the fly and from another process.

There's a great example here with source code provided. Essentially you create a runner that's an exe that executes your cs file.

The runner is a console application. You just pass your CS file in as a parameter. One caveat is that you have to name your class "CSScript". But it would look like the following class. The link uses the CSharpCodeProvider class to compile your source code on the fly.

using System;
using System.Windows.Forms;

class CScript {
    public void Main() {
        // your dynamic code here
    }
}

The example executes the source by dynamically compiling the cs file passed in and then uses reflection to invoke the Main Method.

void ExecuteSource(String sourceText) { CSharpCodeProvider codeProvider = new CSharpCodeProvider();

        ICodeCompiler compiler = codeProvider.CreateCompiler();
        CompilerParameters parameters = new CompilerParameters();
        parameters.GenerateExecutable = false;
        parameters.GenerateInMemory = true;
        parameters.OutputAssembly = "CS-Script-Tmp-Junk";
        parameters.MainClass = "CScript.Main";
        parameters.IncludeDebugInformation = false;

        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
            parameters.ReferencedAssemblies.Add(asm.Location);
        }

        CompilerResults results = compiler.CompileAssemblyFromSource(parameters, sourceText);

        if (results.Errors.Count > 0) {
            string errors = "Compilation failed:\n";
            foreach (CompilerError err in results.Errors) {
                errors += err.ToString() + "\n";
            }
            MessageBox.Show(errors, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }   else {
            object o = results.CompiledAssembly.CreateInstance("CScript");
            Type type = o.GetType();
            MethodInfo m = type.GetMethod("Main");
            m.Invoke(o, null);
            if (File.Exists("CS-Script-Tmp-Junk")) { File.Delete("CS-Script-Tmp-Junk"); }
        }
    }

To call you run a command as follows

CS-SCript.exe yourcsfile.cs
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top