To get your C# code using Python (via Python.Runtime) working in Visual Studio, you need to set up the Python.NET environment.
- Install Python and Locate
python312.dll
Make sure you have installed Python 3.12 (matching your code) from https://www.python.org/downloads/windows/. Next, identify the exact path to python312.dll (usually found in C:\Users\<YourName>\AppData\Local\Programs\Python\Python312\)
- Install Python.NET via NuGet
In Visual Studio:
- Right-click on your project →
Manage NuGet Packages - Search for:
Python.Runtime - Install the version that matches your Python version (e.g.,
Python.Runtime 3.12.xif you have Python 3.12)
Keep in mind that a version mismatch between Python.Runtime and your Python installation will cause runtime errors.
- Manually Set the
Runtime.PythonDLLPath
Before initializing the Python engine, make sure this line is correct:
Runtime.PythonDLL = @"C:\Path\To\python312.dll";
Replace it with the actual path on your machine, for example:
Runtime.PythonDLL = @"C:\Users\YourName\AppData\Local\Programs\Python\Python312\python312.dll";
- Ensure your project is built as x64. Python and Python.NET are architecture-specific. If your Python is 64-bit, do this:
- Right-click project → Properties
- Go to Build tab → Set Platform Target to
x64 - Also do this in the Configuration Manager (in the top toolbar)
- Ensure Python can run this in a standalone script:
from transformers import pipeline
pipeline("text-classification")
If this fails in Python, run:
pip install transformers
Use this code:
using Python.Runtime;
using System;
class Program
{
static void Main()
{
// Update this path!
Runtime.PythonDLL = @"C:\Users\YourName\AppData\Local\Programs\Python\Python312\python312.dll";
PythonEngine.Initialize();
using (Py.GIL())
{
dynamic transformers = Py.Import("transformers");
dynamic pipeline = transformers.pipeline("text-classification");
dynamic result = pipeline("This app is amazing!");
Console.WriteLine(result);
}
PythonEngine.Shutdown();
}
}
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin