I have a c++ program that is writing in a txt file every second and I want to get that data that is being written by c#. so the c++ is only writing and the c# is reading. with my knowledge txt files can't be accessed from 2 diffrent programs at once. what should I do.

Notes : I don't want to use network ( tunnel and ...)

This might not be an ideal solution but you can try copying the file in your C# code and then reading from it and try to keep the file up to date. Depending on the file size i don't think it will be possible to synchronize the two application.

I assume you are using the CreateFile API call to open the file.

In the C++ app you should specify GENERIC_WRITE as the dwDesiredAccess parameter (because you want to write to the file) and FILE_SHARE_READ as the dwShareMode parameter (so that other applications can read the file at the same time).

In your other app you need to specify GENERIC_READ as the access mode (because you want to read the file) and FILE_SHARE_WRITE as the share mode (to allow the C++ app to write to the file).

Copying the file and reading it might cause a data loss, i.e. there might be a few bytes that is still to be written but by that time the copy action is performed. may not be the best option, but can be given a try with this kinda scenario.

Do you have a placeholder (other than the file) , like a DB where the data is stored while the file is written, in that you can read the data from DB through c#.
OR
C# provides FileSystemWatcher class, this has events like changed, deleted etc which will notify you when there is a change in the file on the specified path and so you can write your logic there to read from the previous bytes that might have been missed or just read the recent data that is written.

You might be better using a small database like SQLExpress to write your data to rather than a text file. Sharing read/write access is a dangerous game...

This article has been dead for over six months. Start a new discussion instead.