通过 p/调用读取/写入文件时出现问题 ASP.NET bin 文件夹中

本文关键字:ASP 问题 NET bin 文件夹 调用 读取 文件 通过 | 更新日期: 2023-09-27 18:32:41

我一直在尝试通过我的 ASP.NET 网站通过P/Invoke写入和读取文件。在网站中通过dlls执行此操作时,我面临着文件写入/读取位置的问题。我试图用下面的例子来解释这个问题:

.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;
}

发布网站的构建事件,以将 dll 从上面的项目复制到网站的bin文件夹C++

默认值.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设置为项目输出的当前目录,则一切正常。只是在网站的情况下,要写入或读取文件的目录有点混乱,我真的无法弄清楚如何纠正这一点并使其工作。建议将不胜感激。

通过 p/调用读取/写入文件时出现问题 ASP.NET bin 文件夹中

您仍然遇到许多与上一个问题相同的问题。

这一次你最大的问题就在这里:

strcat(fileDir, "test.txt")

您无法修改fileDir,因为它归 pinvoke 封送器所有。不要将目录传递给本机代码,而是传递文件的完整路径。在托管代码中使用Path.Combine来创建它,并将其传递给本机代码。

extern "C" TEST_API int fnTest(char* filename)
{
    ofstream myfile;
    myfile.open(filename);
    myfile << "Writing this to a file.'n";
    myfile.close();
}

和托管代码

string filename = Path.Combine(
    AppDomain.CurrentDomain.BaseDirectory, "bin", "test.txt");
string txt1 = Functions.fnTest(filename).ToString(); 

在注释中,您解释说需要在本机代码中连接字符串。您需要创建一个本机字符串来执行此操作,因为不允许写入fileDir 。像这样:

string fileName = string(fileDir) + "test.txt";
myfile.open(fileName.c_str());

但是您仍然需要修复读取文件的fnTest1。我对你的另一个问题的回答告诉你如何做到这一点。