The code below creates a form which opens and evaluates my notebook ok.nb
. You will have to figure out how to close the front end while still giving your notebook enough time to evaluate. This demo pauses 5 seconds. There is a more sophisticated option here.
You may be able to omit the CreateKernel()
method and simply call kernel = new MathKernel()
, but that does not work on my setup (which includes multiple Mathematica versions);
using System;
using System.Windows.Forms;
using Wolfram.NETLink;
namespace RunMathematicaNotebook
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
MathKernel kernel = null;
try
{
kernel = CreateKernel();
kernel.Compute("UsingFrontEnd[nb = NotebookOpen[\"C:\\Users\\chrisd\\Documents\\ok.nb\"]; NotebookEvaluate[nb]]");
kernel.Compute("Pause[5]; CloseFrontEnd[]");
}
catch
{
MessageBox.Show("Error connecting to Mathematica", "Mathematica Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
if (kernel != null)
kernel.Dispose();
}
}
public MathKernel CreateKernel()
{
string mlArgs = "-linkmode launch -linkname \"C:\\\\Program Files\\\\Wolfram Research\\\\Mathematica\\\\11.2\\\\MathKernel.exe\"";
IKernelLink ml = MathLinkFactory.CreateKernelLink(mlArgs);
MathKernel mathKernel = new MathKernel
{
AutoCloseLink = true,
CaptureGraphics = true,
CaptureMessages = true,
CapturePrint = true,
GraphicsFormat = "Metafile",
GraphicsHeight = 0,
GraphicsResolution = 80,
GraphicsWidth = 0,
HandleEvents = true,
Input = null,
Link = ml,
LinkArguments = null,
PageWidth = 0,
ResultFormat = MathKernel.ResultFormatType.OutputForm,
UseFrontEnd = true
};
return mathKernel;
}
}
}
As well as adding a reference to Wolfram.NETLink
you will probably need to copy ml32i4.dll
to your project folder and make sure it copies to your output directory. There is some more info about that here.

SystemOpen @FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "NETLink", "Examples", "Part2"}]
$\endgroup$