i am working on a project that requires a folder to be accessed by only w3wp.exe process.
no other user can access this folder on the machine
i am working on a console project my implementation so far is
public static void SetFolderPermission(string folderPath){
bool exists = Directory.Exists(folderPath);
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(folderPath);
Console.WriteLine("The Folder is created Sucessfully");
}
else
{
Console.WriteLine("The Folder already exists");
}
var directoryInfo = new DirectoryInfo(folderPath);
var directorySecurity = directoryInfo.GetAccessControl();
var currentUserIdentity = GetIISProcessID("w3wp");
//WindowsIdentity.GetCurrent();
var fileSystemRule = new FileSystemAccessRule(currentUserIdentity,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit |
InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow);
directorySecurity.AddAccessRule(fileSystemRule);
directoryInfo.SetAccessControl(directorySecurity);
}
and getting the process is
public static int GetIISProcessID(string appPoolName)
{
//return 0;
string commandLine = String.Empty;
Process[] pCollection = Process.GetProcessesByName(appPoolName);
//Process.GetProcessById(7684, "w3wp.exe");
//Process.GetProcessesByName("w3wp.exe");
foreach (Process pInstance in pCollection)
{
ObjectQuery sq = new ObjectQuery
("Select CommandLine from Win32_Process Where ProcessID = '" + pInstance.Id + "'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq))
{
ManagementObjectCollection objectCollection = searcher.Get();
foreach (ManagementObject oReturn in objectCollection)
{
commandLine = oReturn["CommandLine"].ToString(); break;
}
Console.WriteLine(commandLine);
}
}
return 0;
}
can someone help me figuring out this how can i make a process access a folder.
Related
I found the following method to get a process's owner:
public string GetProcessOwner(int processId)
{
string query = "Select * From Win32_Process Where ProcessID = " + processId;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
return argList[1] + "\\" + argList[0];
}
}
return "";
}
This works fine, however it is very slow. I use it in conjunction with Process.GetProcesses() and it takes circa 20 seconds in total to get every process owner. Is there any way to speed this up?
I want to find the pah for the currently opened file which is either currently active in the windows Explorer . i have got the location for the folder while the folder is being clicked but how do we get the path of the file like a text file or word or something like that
private string GetActiveWindowPath()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
int handleint = int.Parse(handle + "");
SHDocVw.ShellWindows explorer = new SHDocVw.ShellWindows();
//var xy = new SHDocVw.InternetExplorerMedium();
var xpl = explorer.Cast<SHDocVw.InternetExplorerMedium>().Where(hwnd => hwnd.HWND == handleint).FirstOrDefault();
if (xpl != null)
{
// this will get the folder location
string path = new Uri(xpl.LocationURL).LocalPath;
return ("location:" + xpl.LocationName + " path:" + path );
}
return "HWND" + handleint ;
}
i ma getting the path of the opened window as you see but not the text file
private string GetMainModuleFilepath(int processId)
{
string wmiQueryString = "SELECT * FROM Win32_Process WHERE ProcessId = " + processId;
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
{
using (var results = searcher.Get())
{
ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
if (mo != null)
{
return (string)mo["CommandLine"];
}
}
}
Process testProcess = Process.GetProcessById(processId);
return null;
}
After that you will get Executable file name with your file name like
"c:..\notepade.exe" D:\New Folder\sampleFile.txt" after that split as you like to get the path.
I have a process a method that successfully stops the process. But how can I start it? It is a .exe file that lays on the remote machines harddrive.
var ui = new ImpersonateUser();
var processName = "notepad.exe";
object[] processArgs = { #"C:\\WINDOWS\notepad.exe" };
try
{
ui.Impersonate(Domain, _userName, _pass);
ManagementPath path = new ManagementPath
{
Server = "serverName",
NamespacePath = "\\ROOT\\CIMV2",
ClassName = "Win32_Process"
};
ManagementScope scope = new ManagementScope(path);
ManagementClass management = new ManagementClass(path);
var query = new SelectQuery("SELECT * from Win32_process WHERE name = '" + processName + "'");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject process in searcher.Get())
{
process.InvokeMethod("Terminate", null); //This work
Thread.Sleep(3000);
management.InvokeMethod("Create", processArgs); //doesnt work. Why ?
}
}
}
How can I make the .exe start after I have shut it down?
You have a typo (D instead of T) in a program name. It should be noTepad.exe and not noDepad.exe Besides I suggest to check results returned by InvokeMethod In your case it returns 9 what means Path Not Found. Here is a full list of codes.
UPDATE
If InvokeMethod returns 0 but you don't see a new instance of notepad on a remote machine it means that it was run in background. However, you should be able to see this new instance in Windows Task Manager.
Is there a way to determine what all users are logged into remote machine, using WMI and C#
After little research I was able to figure it out, although not sure if this is the best way
public void GetCompDet(string ComputerName)
{
CurrentSystem = ComputerName;
ConnectionOptions options = new ConnectionOptions();
ManagementScope moScope = new ManagementScope(#"\\" + ComputerName + #"\root\cimv2");
try
{
moScope.Connect();
}
catch
{
return;
}
ObjectQuery query = new ObjectQuery("select * from Win32_Process where name='explorer.exe'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(moScope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
ManagementOperationObserver mo = new ManagementOperationObserver();
mo.ObjectReady += new ObjectReadyEventHandler(mo_ObjectReady);
m.InvokeMethod(mo, "GetOwner", null);
}
}
void mo_ObjectReady(object sender, ObjectReadyEventArgs e)
{
ManagementObject m = sender as ManagementObject;
LoggedinUser.Enqueue(CurrentSystem + " - >" + e.NewObject.Properties["user"].Value.ToString());
Console.WriteLine(CurrentSystem + " - >" + e.NewObject.Properties["user"].Value.ToString());
}
I want to know the user that created each process.
How do I get the usernames of all the processes running in task manager using c#?
Look into Win32_Process Class, and GetOwner Method
Sample Code
Sample code
public string GetProcessOwner(int processId)
{
string query = "Select * From Win32_Process Where ProcessID = " + processId;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
return argList[1] + "\\" + argList[0];
}
}
return "NO OWNER";
}