C# – Importing a DLL in C#

.netc++dlldllimport

I'm trying to import a dll to my C# project using DllImport as follows:

[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key,string val,string filePath);

Also, I have added the namespace System.Runtime.InteropServices:

using System.Runtime.InteropServices;

Still, I'm getting an error:
"The name 'DllImport' does not exist in the current context"

Is there a limitation on where in a class you can import a dll?

Best Solution

You've probably also got the wrong return type in your statement. Try with bool:

[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(string section, string key,string val,string filePath);

References: http://msdn.microsoft.com/en-us/library/ms725501(v=vs.85).aspx

EDIT:

DllImports have to be placed inside the body of your class. Not inside methods or the constructor.

public class Class1
{
     //DllImport goes here:
     [DllImport("kernel32")]
     private static extern ...

     public Class1()
     {
          ...
     }

     /* snip */
}
Related Question