For learning purposes and mere curiosity I have been trying somehow to kill a process with the characteristics explained above in the title:
1. The name of the file changes every time it is downloaded.
2. Window without a name.
(I can't use PID because I need something that doesn't change to make it automatic)
(The exe name always start with DaxSS-
Example names:
DaxSS-TSFGR
DaxSS-RFDUC
DaxSS-GFFRS
Is there a way to do that?
The downloaded exe name always start with DaxSS
That's your ticket right there!
string start = "DaxSS".ToUpper();
Process P = Process.GetProcesses().Where((p) => p.ProcessName.ToUpper().StartsWith(start)).FirstOrDefault();
if (P != null)
{
P.Kill();
}
In my C# WinForms app, users are allowed to create documents and show them in other programs (typically, Word or Excel) and once users close it (if modified), the file is saved by the app in a specific database.
I use the following code to open the file with the correct default program:
string tmpPath = "myTempDoc.xyz"; // extension might vary
FileInfo f = new FileInfo(tmpPath);
DateTime tmpStamp = f.LastWriteTimeUtc;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(tmpPath);
p.WaitForExit();
f = new FileInfo(tmpPath);
if (f.LastWriteTimeUtc > tmpStamp.AddSeconds(1)) {
db_store_file(tmpPath); // stores the modified version of the file in a database
}
// ---- REMAINING CODE AFTER CLOSING ---
doSomeStuff();
I am a bit concerned with the WaitForExit() method. Users need to close the default program for the app to continue. This is ok, but is it really safe?
What if the user (or some process) kills the App during the WaitForExit? For sure, remaining code doSomeStuff() will NOT be executed so I need to make sure all is done BEFORE starting the process... But is there any additional risk?
I know about FileSystemWatcher could be an alternative... But this allows the user to continue in the app without saving changes, which is an additional risk I'd rather not take...
Is the above method safe? Or is there a standard method for letting users modify files in their default program and, once done, retrieve these changes in the database?
I am using the JitBit Macro Recorder to create "bots" that save me a lot of time at work. This program can use the mouse and the keyboard and perform tasks by checking different if-options like "if image found on screen".
My newest "bot" is about 900 lines of commands long and I would like to make a log-file to find an error somewhere in there. Sadly, this program doesn't offer such an option, but it let's me use c# as a task. I have NO experience with c# but I thought, that this is easy to do for someone who has some experience.
If I click execute c# code, I get the following input field:
Important: This code MUST contain a class named "Program" with a static method "Main"!
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
Now I need two code templates:
1. Write a message to a "bot_log.txt" located on my desktop.
[19.05.2016 - 12:21:09] "Checking if item with number 3 exists..."
The number "3" changes with every run and is an exact paste of the clipboard.
2. Add an empty line to the same file
(Everything should be added to a new line at the end of this file.)
If you have no idea how to program in C#, then you should learn it,
if you want to use code provided from answers.
And if you want to generate timestamps and stuff then it's not done within minutes and I don't think someone writes the whole code just for your fitting. Normally questions should have at least a bit of general interest.
Anyway:
This works, if you have a RichTextTbox in your program.
Just do a new event (like clicking a button) and do this inside it.
(This was posted somewhere here too or on another site, with sligh changes)
public static void SaveMyFile(RichTextBox rtb)
{
// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveLog = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the RTF extention for the file.
saveLog.DefaultExt = "*.rtf";
saveLog.Filter = "RTF Files|*.rtf"; //You can do other extensions here.
// Determine whether the user selected a file name from the saveFileDialog.
if (saveLog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveLog.FileName.Length > 0)
{
// Save the contents of the RichTextBox into the file.
try
{
rtb.SaveFile(saveLog.FileName);
}
catch
{
MessageBox.Show("Error creating the file.\n Is the name correct and is enough free space on your disk\n ?");
}
MessageBox.Show("Logfile was saved successful.");
}
}
In my project, I am integrating Matlab GUI application with in a C# application.
The solution I thought about is to create a standalone application from the Matlab GUI and start it via a button in C#:
Process exeProcess = Process.Start("Data_Capture_Direct_call.exe");
if(!exeProcess.HasExited)
{
exeProcess.WaitForExit();
}
exeProcess.Close();
The problem is that after the splash screen of Matlab GUI is closed and before the actual program opens, C# detects that the program has been closed already and carries on to the next line.
In addition, the next few lines of code are not properly executed:
List<String> Movement = new List<String>();
List<String> Repetition = new List<String>();
List<String> Duration = new List<String>();
using (CsvFileReader reader = new CsvFileReader("capture.csv"))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
Movement.Add(row[0]);
Repetition.Add(row[1]);
Duration.Add(row[2]);
}
}
for (int i = 1; i < Movement.Count; i++)
{
dataGridView1.Rows.Add(i, Movement[i], Repetition[i], Duration[i]);
}
What happens is that after the C# wrongly detects closure of the process, the capture.csv file becomes empty and data is not loaded into the data grid.
Please let me know where I am making a mistake or if there is a better way to do this!
In my solution you should do some settings before starting code in order to use Matlab instance in a C# application.
Adding neccessary dll :
First we will add dll reference with COM interface. Click RMB on project and choose [Add Reference] option. In new window click COM tab. In search text box write 'Matlab'. Then choose "Matlab Application (Version 7.10) Type Library".
You should get references like below :
Now you can easily do whatever you can do on Matlab in C# . Lets give an basic example :
var acCtx = Type.GetTypeFromProgID("matlab.application.single");
var matlab = (MLApp.MLApp)Activator.CreateInstance(acCtx);
these two lines are creating of matlab instance in code.Now let's make a easy computation on Matlab.
Console.WriteLine(matlab.Execute("1+2")); // This will output 3 on console.
matlab.Quit(); // you should close matlab in order to clean memory
Lets give solution to your actual problem.You want to execute a Matlab GUI program.And I think your Gui is recording some data to CSV file.Then your C# program processes that data.You should note that you can call your GUI in Matlab just writing your name of program as command.Suppose that you have a GUI called myGui.m.You can call that gui by calling myGui in command line as you can write 1+2 to get 3.
Let's call gui.
matlab.Execute("myGui"); // This will execute your Gui. You can use buttons to save data to CSV file
matlab.Quit();
I have extended example on this page :
Source
I using C# .NET , vs 2008 , .net 3.5
For me, is difficult, but I need sample code in C# for this:
Check if a file or a folder is in use
If file or a folder is in use, the name of Process that use it
For example, in my issue.
I try delete file, and I get "The process cannot access the file 'XYZ' because it is being used by another process." Exception.
File.Delete(infoFichero.Ruta);
I want check if a file is in use, and the name of Process that use it.
I need sample code, source code, please. I dont want use c++, I dont know c, c++, unmanaged code, or WinApi. I want use only C# code (managed code .net).
I have read several references but not get sample code source,
How to check if a file is in use?
Emulate waiting on File.Open in C# when file is locked
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/9dabc172-237a-42db-850e-ada08885a5d5
How to check if a file is in use?
Easiest way to read text file which is locked by another application
Using C# is it possible to test if a lock is held on a file
EDIT:
From Yan Jun - MSFT
string path = "D:\\temp2.xlsx";
foreach (Process c in Process.GetProcesses()) {
if (c.MainWindowTitle.Contains(Path.GetFileName(path))){
MessageBox.Show(c.ProcessName);
return;
}
}
try{
FileInfo f = new FileInfo(path);
f.Delete();
}
catch (Exception ex){
MessageBox.Show(ex.Message);
}
...
But it is difficult get solution for all 100% issues.
Problem if c.MainWindowTitle == null or not contains filename.
Problem for shared folder in another machine, PC, server,... like:
File.Delete(#\desiis\TEmporal\Project\script.targets);
any sample code, I ask for help gurus, MVPs, anyone.
UPDATE: the same issue for a folder
There's not going to be a way to find the process that has the file opened without stepping into the WinApi, I don't think. And as far as checking whether its in use, the only thing you can really do, as the SO questions you linked to state, is to wrap the file access attempts in a try/catch block.
The code to find which file has it opened is likely to be ugly, but there may be an API out there that wraps this up nicely. There are 3rd party utilities that will tell you this (Unlocker being the best known example). You can also use ProcessExplorer to search for open file handles by the filename. Those don't really help you though.
The short answer of what I'm trying to get across here is you have the answer for the first part of your question in the SO questions you already linked, and the second part would probably require WIN32 calls, which you want to avoid, but you're probably going to have to get your hands dirty in Win32... Still want help?
EDIT: You could shell out to sysinternals Handle utility. You would need to get the output of that command and parse it yourself. You can read the executed process's output like this
string result = proc.StandardOutput.ReadToEnd();
The issue with this is you're going to get a license agreement popup the first time you run the Handle utility. Not to mention the whole licensing issues if this is something you hope to deploy...
If you're still interested, I can show you how you'd go about this.
EDIT: Here's a runnable program that will find the exe name and pid of any program that has an open handle to a file. I added comments, but can elaborate further if necessary. I use Regular Expressions here to parse the output as that makes the most sense given the task at hand.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = "handle.exe"; //name of the handle program from sysinternals
//assumes that its in the exe directory or in your path
//environment variable
//the following three lines are required to be able to read the output (StandardOutput)
//and hide the exe window.
si.RedirectStandardOutput = true;
si.WindowStyle = ProcessWindowStyle.Hidden;
si.UseShellExecute = false;
si.Arguments = "test.xlsx"; //this is the file you're trying to access that is locked
//these 4 lines create a process object, start it, then read the output to
//a new string variable "s"
Process p = new Process();
p.StartInfo = si;
p.Start();
string s = p.StandardOutput.ReadToEnd();
//this will use regular expressions to search the output for process name
//and print it out to the console window
string regex = #"^\w*\.EXE";
MatchCollection matches = Regex.Matches(s, regex, RegexOptions.Multiline);
foreach (var match in matches)
{
Console.WriteLine(match);
}
//this will use regex to search the output for the process id (pid)
//and print it to the console window.
regex = #"pid: (?<pid>[0-9]*)";
matches = Regex.Matches(s, regex, RegexOptions.Multiline);
foreach (var obj in matches)
{
Match match = (Match)obj; //i have to cast to a Match object
//to be able to get the named group out
Console.WriteLine(match.Groups["pid"].Value.ToString());
}
Console.Read();
}
}
}
There is no purely managed way to do this. You have to use some low-level APIs through P/invoke or similar.
There's good information here on a way to do it, but it's C++ code. You'd have to do the porting yourself.
http://www.codeproject.com/KB/shell/OpenedFileFinder.aspx
Note there are some complex issues with this, namely the issues around kernel vs. userspace memory. This is not a simple problem you're trying to solve.
Try the windows Process Explorer:
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
Won't let you do it from code, but at least you can figure out what the source of your locks are.