我一直試圖通過我的ASP.NET網站通過P/Invoke來編寫和讀取文件。我在網站上通過dlls
執行此操作時遇到了文件寫入/讀取位置的問題。我試圖解釋與下面的例子問題:通過在ASP.NET bin文件夾中的P/Invoke讀取/寫入文件問題
.cpp文件(包括讀,寫功能)
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;
}
後建立網站的情況下,從上述C,複製dll的++項目網站的bin
文件夾
Default.aspx.cs - C#
DLL函數
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事件
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
如果我試圖在桌面應用程序相同的Page_Load代碼direc
被設置爲項目輸出的當前目錄下,一切工作正常。只有在網站的情況下,要寫入或讀取文件的目錄纔會變得混亂,而我實際上無法弄清楚如何解決此問題並使其正常工作。建議將不勝感激。
您已經提出了完全相同的問題。答案也是一樣的。將完整路徑傳遞給您的本機代碼。我在你之前的問題上的回答甚至解決了你返回字符串的錯誤。 – 2012-04-27 16:11:43
@DavidHeffernan:這次傳遞完整的路徑,就像上面寫的那樣,現在錯誤已經改變了。所以,爲我嘗試過的東西寫了一篇新文章,但仍有錯誤 – user1240679 2012-04-27 16:13:44
您沒有將完整路徑傳遞給該文件。你剛剛通過了目錄。所以你不能'strcat',因爲它增加了'fileDir'的結尾,你不能寫入那個內存,因爲它是由pinvoke編組所擁有的。在上一個問題中,你沒有注意到我答案的後半部分。 – 2012-04-27 16:16:48