C++ CFile 与 C# 应用共享不起作用

C++ CFile sharing with C# App not working?

本文关键字:共享 不起作用 应用 CFile C++      更新时间:2023-10-16

我无法让一个文件创建和填充一个 c++ 应用程序,以便在它仍然在 C++ 应用程序中打开时由不同的 C# 应用程序读取。

我用以下行创建文件:

txtFile.Open(m_FileName, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite, &e)

我也尝试使用以下行:

txtFile.Open(m_FileName, CFile::modeCreate|CFile::modeWrite|CFile::shareDenyNone, &e)

和:

txtFile.Open(m_FileName, CFile::modeCreate|CFile::modeWrite, &e)

结果相同。

然后在 c# 应用程序中,我尝试了 2 种不同的打开文件的方法:

FileStream fs = File.OpenRead(inputfilepath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

byte[] buffer;
using (FileStream stream = new FileStream(inputfilepath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
    buffer = new byte[stream.Length];
    stream.Read(buffer, 0, buffer.Length);
}

两种方法都会捕获错误:

该进程无法访问文件"文件名.txt,因为它正被另一个进程使用。

c++ 应用创建文件,然后使用 CreateProcess 运行 c# 应用。

我希望问题出在 c# 代码中,当我在 c++ 应用程序中添加共享权限时,我尝试将文件作为记事本读取不会出错,但在未设置权限时确实会出现错误。

最后,在Soonts的建议下,我让它按照我想要的方式工作。

将 c++ 文件共享选项设置为:

txtFile.Open(m_FileName, CFile::modeCreate|CFile::modeWrite|CFile::shareDenyWrite, &e)

允许 c# 应用程序读取文件,但不写入文件。

在 C# 应用中,使用以下命令读取文件:

using (FileStream stream = new FileStream(inputfilepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))

将文件访问权限设置为只读。但是,将文件共享权限设置为读写允许在另一个应用程序写入文件时打开文件。我出错的地方是仅读取文件共享权限,因为它在打开文件之前与c ++应用程序冲突。所以它不会打开。

在C++中,指定 CFile::shareDenyNone 或 CFile::shareDenyWrite(就像你正在做的那样)

在 C# 中,指定 FileShare.Write 或 FileShare.ReadWrite。