Search code examples
c#c++cfile

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


I'm having trouble getting a file created and populated with a c++ application to be read by a different c# application while it's still open in the c++ application.

I create the file with the line:

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

I've also tried using the lines:

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

and:

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

with the same results.

Then in the c# app I've tried 2 different ways of opening the file:

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

and

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

Both methods catch the error:

The process cannot access the file 'filename.txt' because it is being used by another process.

The c++ app creates the file, then uses CreateProcess to run the c# app.

I expect the issue to be in the c# code where I try read the file as notepad gives no errors when I add share permissions in the c++ app, but does give errors when I don't set permissions.

In the end I got it to work the way I wanted with Soonts' suggestion.

Setting the c++ fileshare option to:

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

Lets the c# application read the file, but not write to it.

in the c# app reading the file with:

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

Sets the file access to read only. But setting the file share permissions to readwrite allows the file to be opened while it's being written to by another application. Where I went wrong was having the fileshare permissions be read only as it conflicted with the c++ application before the file was even opened. So it wouldn't open.


Solution

  • In C++, specify CFile::shareDenyNone or CFile::shareDenyWrite (like you're doing)

    In C#, specify FileShare.Write or FileShare.ReadWrite.