5

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?

3
  • Could you decribe where exactly in your class you placed your DLLImport statement? Commented Jul 20, 2011 at 7:23
  • I've tried placing it in the constructor of my class. Also tried placing it in some other function. Commented Jul 20, 2011 at 7:26
  • Well, thats the problem. Have a look at the updated answers now. :) Commented Jul 20, 2011 at 7:39

4 Answers 4

10

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 */ } 
Sign up to request clarification or add additional context in comments.

1 Comment

Changed that. Still not working. Its not recognizing DllImport at all. The function line would be executed after it recognizes it i guess.
2

In your solution explorer, right-click references, select Add Reference, and add the System.Runtime.InteropServices to your project.

You can't do using <assembly>; if it's not also referenced in your project.

EDIT

Actually, just saw your comment on your question. I think (haven't done Interop in a while) that it has to be outside a function, in the body of the class.

i.e.:

public class MyClass { [DLLImport("kernel32")] private static extern long WritePrivateProfileString(string sectio, string key, string val, string filePath); public MyClass() { } public void foo() { } // etc, etc } 

1 Comment

I'm doing using <namespace>; The assembly need for this is mscorlib.dll which AFAIK, is referenced automatically.
0

Try Adding these parameters

[DllImport("kernel32",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)] 

1 Comment

Still not working. Its not recognizing DllImport at all. The parameters would come after it recognizes it i guess.
-1

usually when importing win dll you use unsafe code sow be sure to check the project settings here are two simple tutorial that shows the code

code for Kenler32.dll inport

MSDN whit explanation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.