blez's : blog

code / design / music and more

How to read file while it’s in use?

1 Comment

Let’s say you have to use a file which another process locked. You’ll get an error trying to open it. Of course there’s a workaround.
Just duplicate the handle for the current process:


// NOTE:
//
// PID is the process's ID who opened the file (ex. firefox -> 1234)
// hFile is the original file's handle (you can get it using NtQuerySystemInformation)

HANDLE hFileNew;
HANDLE hSourceProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, PID);
DuplicateHandle(hSourceProcess, hFile, GetCurrentProcess(), &hFileNew, DUPLICATE_SAME_ACCESS, TRUE, DUPLICATE_SAME_ACCESS);

// Now you have a new file handle in hFileNew, which you can use with ReadFile or similar
//
// ANOTHER NOTE:
//
// hFileNew's file pointer will have the last position from PID.
// If you change it, it will change for PID too (which can cause a crash or messed up stuff).
// But if you do it fast or pause the process, everything should be fine.

Related: Enumerating opened handles from a process

Advertisements

One thought on “How to read file while it’s in use?

  1. Pingback: Enumerating opened handles from a process « blez's : blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s