通过 p/调用读取/写入文件时出现问题 ASP.NET bin 文件夹中
Issue in Reading/Writing files through P/Invoke in ASP.NET bin folder
我一直在尝试通过我的 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
设置为项目输出的当前目录,则一切正常。只是在网站的情况下,要写入或读取文件的目录有点混乱,我真的无法弄清楚如何纠正这一点并使其工作。建议将不胜感激。
您仍然遇到许多与上一个问题相同的问题。
这一次你最大的问题就在这里:
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
。我对你的另一个问题的回答告诉你如何做到这一点。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 通过 p/调用读取/写入文件时出现问题 ASP.NET bin 文件夹中