I have been trying to write and read files through P/Invoke via my ASP.NET website. I am facing a problem as to where the files are written/read when doing this through dlls in a website. I have tried to explain the problem with the below example:
.cpp file (containing a read and write function)
extern "C" TEST_API int fnTest(char* fileDir)
{
ofstream myfile;
myfile.open (strcat(fileDir, "test.txt"));
myfile << "Writing this to a file.\n";
myfile.close();
}
extern "C" TEST_API char* fnTest1(char* fileDir)
{
ifstream myReadFile;
myReadFile.open(strcat(fileDir, "test1.txt"));
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
return output;
}
Post build event of website to copy the dll’s from above C++ project to website’s bin folder
Default.aspx.cs – C#
Dll functions
public static class Functions(){
DllImport[("Test1.dll", EntryPoint="fnTest", CharSet=CharSet.Ansi]
public static extern int fnTest(string dir);
DllImport[("Test1.dll", EntryPoint="fnTest1", CharSet=CharSet.Ansi]
public static extern StringBuilder fnTest1(string dir);
}
Page_Load event
string direc = AppDomain.CurrentDomain.BaseDirectory + "bin\\";
string txt1 = Functions.fnTest(direc).ToString(); //failing here - keeps on loading the page forever
string txt2 = Functions.fnTest(direc).ToString(); //failing here - keeps on loading the page forever
If I try the same Page_Load code in a desktop application with direc being set as current directory of the project output, everything works fine. It’s only that the directories where the files are to be written or read are kind of messed in case of web site and I am not really able to figure out how to correct this and get it working. Suggestions would be greatly appreciated.
You still have a number of the same problems as you have in the last question.
This time round your biggest problem is here:
You can’t modify
fileDirsince it is owned by the pinvoke marshaller. Instead of passing the directory to your native code, pass the full path to the file. UsePath.Combinein your managed code to create that, and pass it to the native code.and in managed code
In a comment you explain that you need to concatenate strings in the native code. You will need to create a native string to do that because you are not allowed to write to
fileDir. Something like this:But you still need to fix
fnTest1which reads the file. My answer at your other question tells you how to do that.