W
Willy Denoyette [MVP]
You can't find the files opened by a specific process, however it's possible
to get the process(es) that has a specific file open.
Here's a sample:
public static void Main() {
WhoHasThisFileOpen(@"c:\\filepath");
}
static void WhoHasThisFileOpen(string objectQry) {
SelectQuery query = new SelectQuery("select name from cim_datafile where
name ='" + objectQry +"'" );
using(ManagementObjectSearcher searcher = new
ManagementObjectSearcher(query)) {
foreach (ManagementObject mo in searcher.Get()) {
Console.WriteLine("File Name: {0} \nIs currently opened by:",
mo.Properties["Name"].Value);
// Get processes having this File open
foreach (ManagementBaseObject b in mo.GetRelated("Win32_Process")) {
ShowProcessProperties(b.ToString());
}
}
}
}
static void ShowProcessProperties(string objectClass) {
using(ManagementObject process = new ManagementObject (objectClass))
{
process.Get();
PropertyDataCollection processProperties = process.Properties;
Console.WriteLine("ProcessID: {0,6} \tCommandLine: {1}" ,
processProperties["ProcessID"].Value,
processProperties["CommandLine"].Value);
}
}
}
Willy.
to get the process(es) that has a specific file open.
Here's a sample:
public static void Main() {
WhoHasThisFileOpen(@"c:\\filepath");
}
static void WhoHasThisFileOpen(string objectQry) {
SelectQuery query = new SelectQuery("select name from cim_datafile where
name ='" + objectQry +"'" );
using(ManagementObjectSearcher searcher = new
ManagementObjectSearcher(query)) {
foreach (ManagementObject mo in searcher.Get()) {
Console.WriteLine("File Name: {0} \nIs currently opened by:",
mo.Properties["Name"].Value);
// Get processes having this File open
foreach (ManagementBaseObject b in mo.GetRelated("Win32_Process")) {
ShowProcessProperties(b.ToString());
}
}
}
}
static void ShowProcessProperties(string objectClass) {
using(ManagementObject process = new ManagementObject (objectClass))
{
process.Get();
PropertyDataCollection processProperties = process.Properties;
Console.WriteLine("ProcessID: {0,6} \tCommandLine: {1}" ,
processProperties["ProcessID"].Value,
processProperties["CommandLine"].Value);
}
}
}
Willy.