In C++ WinAPI application I open the file using this code
CreateFileW(path,FILE_APPEND_DATA,FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
While the file is opened by this C++ app, I’m trying to open it for reading in C# app, using this code
var f = new StreamReader(path);
I get IOException “The process cannot access the file because it is being used by another process”
I tried
var fs = new FileStream(path, FileMode.Open,FileAccess.Read)
Same result.
I can’t understand why this is happening. I specified FILE_SHARE_READ in CreateFile in my C++ app. I open it for reading in C#. It must open in C# app. What am I doing wrong?
At the same time, notepad.exe can open this file
The FileStream constructor you’re using in the C# app opens the file with the FileShare.Read option, equivalent to FILE_SHARE_READ.
This means that other programs are allowed to have the file open for reading, but not for writing, while you have the file open. But your C++ program already has the file open for writing, so the sharing mode you’ve requested isn’t possible and the attempt to open the file fails.
Instead, say this: