How to get last process that has written on a file C#

swodniW 141 Reputation points
2021-04-07T11:11:53.807+00:00

Hello, C#

How can i get the last process that has written on a file?
for example example.exe writes 'A' in a file, another process called Getter.exe(monitors the file) get example.exe

Is there an API?
Thanks in advance

C#

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,412 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,175 questions
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 31,556 Reputation points
    2021-04-11T15:57:29.45+00:00

    I would think that the easiest solution would be to enable file auditing and then analyze the security event log. You could use the task scheduler and trigger on an event being written.

    https://www.varonis.com/blog/windows-file-system-auditing/

    I followed the link that cooldadtx provided and I could not find anywhere that process name was made available. Writing your own driver as Castorix31 offered will be challenging. Can you just use Process Monitor and filter on a file or folder name?

    Perhaps if you could take a step back and explain the overall problem that you are trying to solve, maybe some forum user might have alternative idea. IE: what is the real problem that you are trying to solve?

    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Michael Taylor 47,471 Reputation points
    2021-04-07T14:07:43.733+00:00

    There is no API that tracks what process wrote to a file. The only thing the file system stores is the last write time in this regard.

    The assumption here is that you want this after the fact. While your app is running you can get notifications from the system when a file is written but it doesn't provide any details about who. To do that you'll need to look into the FileSystemWatcher.

    1 person found this answer helpful.
    0 comments No comments

  2. Viorel 111.5K Reputation points
    2021-04-07T20:43:53.523+00:00

    If these processes are made by you, I think that it is possible to design a custom file format for your specific purposes.

    1 person found this answer helpful.
    0 comments No comments

  3. Castorix31 81,356 Reputation points
    2021-04-08T05:25:13.943+00:00

    One of the only ways is to use a File System Driver and intercep IRP_MJ_WRITE
    (a tool like Process Monitor does that)

    1 person found this answer helpful.
    0 comments No comments

  4. swodniW 141 Reputation points
    2021-04-11T14:34:40.153+00:00

    Thanks guys, is it possible to use the event register instead of a driver?
    Thanks in advance