Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a DLL in C#

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?

like image 912
sohil Avatar asked Jul 20 '11 07:07

sohil


People also ask

What are DLL files in C?

In Windows, a dynamic-link library (DLL) is a kind of executable file that acts as a shared library of functions and resources. Dynamic linking is an operating system capability. It enables an executable to call functions or use resources stored in a separate file.

What is DLL import?

DllImport Attribute is a declarative tag used in C# to mark a class method as being defined in an external dynamic-link library (DLL) rather than in any . NET assembly.


1 Answers

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 */
}
like image 84
Emiswelt Avatar answered Sep 24 '22 10:09

Emiswelt