Check if the process exists before process.start(); - c#

I made a little program that execute executable file (.exe) but when you write down no existed file I get an error, the file specific not found.
So I'm wondering if there's a way to check if the process exists first before running it, and if it doesn't exist you can show a message box.
This is my code
private void btn_Start_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
Process process = new Process();
if (!textBox1.Text.Contains(".exe"))
{
process.StartInfo.FileName = text + ".exe";
}
else
{
process.StartInfo.FileName = text;
}
process.Start();
}

Check that file is exists before start process:
var processFileName = !textBox1.Text.Contains(".exe")
? text + ".exe"
: text;
if (File.Exists(processFileName))
{
Process process = new Process();
process.Start(processFileName);
}

Please try the following code:
->(You have to add #using System.IO; before using "File.Exists" command)
button1_Click(object sender, EventArgs )
{
string exepath = "C:\\example\\example.xlsx";
if(File.Exists(exepath))
{
Process.Start(exepath);
}
else
{
MessageBox.Show("File not found!");
}
}
Hope it's working !
You can string the path and string the filename in other string, and then you can even check the Folder, and if the folder exists ,then check the file!
Also you can use your textbox1 as filename, but you have to add the path, unless it will be search in the program directory.(bin/debug)
If i was wrong, forgive me, i am learning c# at the moment!
Have a good day!

Related

throwing UnauthorizedAccessException when accessing an image file

I have a problem with accessing and copying an image file. Here my code
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
string fileName = "";
fileName = openFileDialog1.FileName;
string newPath = #"C:\Users\grafik5\source\repos\ConsoleApplication1\x64\Debug";
string newFileName = #"image";
string ext = Path.GetExtension(fileName);
openFileDialog1.Dispose();
newPath = Path.Combine(newPath, newFileName + ext);
if (fileName != "")
{
try
{
FileSecurity oFileSecurity = new FileSecurity();
oFileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(fileName, oFileSecurity);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Error");
}
File.Copy(fileName, newPath, true);
Process process = new Process();
process.StartInfo.FileName = #"C:\Users\grafik5\source\repos\ConsoleApplication1\x64\Debug\ConsoleApplication1.exe";
process.Start();
process.WaitForExit();
flag1 = true;
}
}
I don't know what I need to do. My program always throws the error message.
Another process will read the copied image. It will do image processing.
There is no problem with the process of working. I checked it.
Error is at File.SetAccessControl(fileName, oFileSecurity);
Any young Codeling Jedi should have looked at the documentation, which i assume you have. However -
File.SetAccessControl Method (String, FileSecurity)
Applies access control list (ACL) entries described by a FileSecurity
object to the specified file.
Exceptions
UnauthorizedAccessException
The path parameter specified a file that is read-only.
This operation is not supported on the current platform.
The path parameter specified a directory.
The caller does not have the required permission.
This is probably a permissions thing. The easiest fix, is make sure your application has the appropriate permissions to do this.
Either
Elevate your app by running it as Administrator,
Give your user the appropriate permissions to set the ACL
However it should be wise and prudent, to check if the other conditions apply

Reading the correct directory

I've tested the code and the directory gets the correct input, but for some reason it can't find it. Is there something I'm missing why I can't find any directory?
Here is my code pretty simplistic as of right now.
public partial class Form1 : Form
{
string fileName;
string dirName;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dirName = textBox1.Text;
fileName = textBox2.Text;
if (System.IO.Directory.Exists(dirName))
{
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
else
{
MessageBox.Show("Invalid Directory or File Name");
}
}
}
That's because I guess you're passing the directory path by an input control in this way "C:/examplePath/" and it should be declared in this way "C:\\examplePath" because the escape characters, and probably you'll get another error further because when you're asking for a file's existence, you must to declare it concatenating directory path plus filename (and its extension).
so the final string should be like this "c:\\exampleDir\\examplefile.ext"
or simply you should try:
dirName = string.Format("#{0}", textBox1.Text);
fullPathFile = string.Format("{0}/{1}", dirName, textBox2.Text);
And then you use "fullPathFile" instead of "fileName" variable.
Don't forget to debug your application for making sure what's the string values.
Based on your code, it appears fileName and dirName come from two different textbox controls. And you also dont do any sort of combining the file path (or so it appears). So when you call Directory.Exists() it makes sense that this would work but it can't find the file. When you use File.Exists() you need to pass in not only the file name but also the directory where its located. To do this use the Path.Combine() method.
if (System.IO.Directory.Exists(dirName))
{
string filePath = System.IO.Path.Combine(dirName, fileName);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
else
{
MessageBox.Show("Invalid Directory or File Name");
}
}

Open link in browser from code behind of installed application C#

I have made a winform application. When I run the app in visual studio, following code works to open a link from DataGridView link column.
System.Diagnostics.Process.Start("chrome.exe",
grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
But when I install the build and try to do the same thing, nothing happens. Is there any other setting that I need to make.
Please help.
If you want to open link link from your DataGridView, you should actually pass url not web browser, ie.:
System.Diagnostics.Process.Start(grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
It will end up trying to open given url with default browser for OS.
Ofc make sure that link of url from url is properly formatted.
If chrome.exe doesn't work for launching, maybe try shortened one: chrome?
Can you also confirm that Win+R (a.k.a. Run...) and then chrome.exe actually opens up Chrome?
If not, can you check if
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\ contains chrome.exe entry?
If so, maybe url formatting is wrong?
You can open a URL in browser with the following snippets:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = "http://google.com";
process.Start();
or
System.Diagnostics.Process.Start("http://google.com");
In your example, to allow users to launch it from the DataGridView, you should simply define a click event like this:
private void grdRelLinks_CellContentClick(object pSender, DataGridViewCellEventArgs pArgs)
{
if (pArgs.RowIndex > -1 && pArgs.ColumnIndex == 2)
{
string url = grdRelLinks.Rows[pArgs.RowIndex].Cells[pArgs.ColumnIndex].Value.ToString();
if(!string.IsNullOrWhiteSpace(url))
System.Diagnostics.Process.Start(url);
}
}
This worked for me.
private void OnGridViewContentClick(object sender, EventArgs e)
{
string chromeExePath = CheckIfChromeIsInstalled();
if (!string.IsNullOrEmpty(chromeExePath))
{
MessageBox.Show("Yayy Chrome.exe was found !");
//Path is not null:
Process.Start(chromeExePath, "http://www.google.de");//Here you can also enter the URL you get from your GridView
string url = grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString();
if(!url.StartsWith("http")
{
url = $"http://{url}";
}
Process.Start(chromeExePath, url);
}
else
{
MessageBox.Show("Chrome.exe not found");
}
}
private string CheckIfChromeIsInstalled()
{
DirectoryInfo programFiles = new DirectoryInfo(Environment.GetEnvironmentVariable("PROGRAMFILES"));//Find your Programs folder
DirectoryInfo[] dirs = programFiles.GetDirectories();
List<FileInfo> files = new List<FileInfo>();
Parallel.ForEach(dirs, (dir) =>
{
files.AddRange(dir.GetFiles("chrome.exe", SearchOption.AllDirectories)); //Search for Chrome.exe
});
//files should only contain 1 entry
//Return path of chrom.exe or null
return (files.Count > 0) ? files[0].FullName : null;
}
NOTE: Starting this in an extra Thread could be useful !
EDIT :
Can you please check if cmd.exe works with start chrome.exe "your URL" ?!

How do you open a local html file in a web browser when the path contains an url fragment

I am trying to open a web browser via the following methods. However, when the browser opens the url / file path, the fragment piece gets mangled (from "#anchorName" to "%23anchorName") which does not seem to get processed. So basically, the file opens but does not jump to the appropriate location in the document. Does anyone know how to open the file and have the fragment processed? Any help on this would be greatly appreciated.
an example path to open would be "c:\MyFile.Html#middle"
// calls out to the registry to get the default browser
private static string GetDefaultBrowserPath()
{
string key = #"HTTP\shell\open\command";
using(RegistryKey registrykey = Registry.ClassesRoot.OpenSubKey(key, false))
{
return ((string)registrykey.GetValue(null, null)).Split('"')[1];
}
}
// creates a process and passes the url as an argument to the process
private static void Navigate(string url)
{
Process p = new Process();
p.StartInfo.FileName = GetDefaultBrowserPath();
p.StartInfo.Arguments = url;
p.Start();
}
Thanks to all that tried to help me with this issue. I have since found a solution that works. I have posted it below. All you need to do is call navigate with a local file path containing a fragment. Cheers!
private static string GetDefaultBrowserPath()
{
string key = #"HTTP\shell\open\command";
using(RegistryKey registrykey = Registry.ClassesRoot.OpenSubKey(key, false))
{
return ((string)registrykey.GetValue(null, null)).Split('"')[1];
}
}
private static void Navigate(string url)
{
Process.Start(GetDefaultBrowserPath(), "file:///{0}".FormatWith(url));
}
All you need is:
System.Diagnostics.Process.Start(url);
Try relying on the system to resolve things correctly:
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.FileName = "http://stackoverflow.com/questions/tagged/c%23?sort=newest&pagesize=50";
p.StartInfo.Verb = "Open";
p.Start();
}
I am not a C# programmer, but in PHP I would do a urlencode. When I did a Google search on C# and urlencode it gave this page here at StackOverflow... url encoding using C#

Certain Python commands aren't caught in Stdout

I've written a simple program that captures and executes command line Python scripts, but there is a problem. The text passed to a Python input function isn't written to my program despite my program capturing stdout.
For example:
The Python script:
import sys
print("Hello, World!")
x = input("Please enter a number: ")
print(x)
print("This work?")
Would write "Hello, World!" then stop. When I pass it a number it would continue on writing "Please enter a number: 3". What is going on? Any solutions? My C# is as follows:
public partial class PyCon : Window
{
public string strPythonPath;
public string strFile;
public string strArguments;
private StreamWriter sw;
public PyCon(string pythonpath, string file, string args)
{
strPythonPath = pythonpath;
strFile = file;
strArguments = args;
InitializeComponent();
Process p = new Process();
p.StartInfo.FileName = strPythonPath;
p.StartInfo.Arguments = "\"" + strFile + "\" " + strArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
sw = p.StandardInput;
}
private void p_OutputDataReceived(object sendingProcess, DataReceivedEventArgs received) {
if (!String.IsNullOrEmpty(received.Data)) {
AppendConsole(received.Data);
}
}
private void p_ErrorDataReceived(object sendingProcess, DataReceivedEventArgs received) {
if (!String.IsNullOrEmpty(received.Data)) {
AppendConsole(received.Data);
}
}
private void AppendConsole(string message) {
if (!txtConsole.Dispatcher.CheckAccess()) {
txtConsole.Dispatcher.Invoke(DispatcherPriority.Normal, (System.Windows.Forms.MethodInvoker)delegate() { txtConsole.AppendText(message + "\n"); });
} else {
//Format text
message = message.Replace("\n", Environment.NewLine);
txtConsole.AppendText(message + "\n");
}
}
private void txtInput_KeyUp(object sender, KeyEventArgs e) {
if (e.Key != Key.Enter) return;
sw.WriteLine(txtInput.Text);
txtInput.Text = "";
}
}
Edit: After a lot of research and help from this thread, I've come to the conclusion that the problem is with the Python input command not calling the C# DataReceivedEventHandler. There may not be a solution to this besides scripting changes. If that is the case, I'll make the answer containing those changes as accepted. Thanks for the help, guys!
Smells like the Python i/o is line buffered, i.e. waits for a CRLF then sends a whole line at once. You could try turning that off (python -u myscript.py, or set the PYTHONUNBUFFERED environment variable) or work around it with something like this:
print("Hello, World!")
print("Please enter a number: ")
x = input()
print(x)
It's difficult to tell because I'm using python 2.6 and you appear to be using 3.x, and I also have not programmed in c# for quite awhile but my guess is that this line:
sw.WriteLine(txtInput.Text);
Is sending "3" plus a windows new line character.
Try:
sw.Write(txtInput.Text + "\n")
sw.Flush()
This will just send a normal newline instead of a windows carriage return which may be the issue. Make sure you always Flush when dealing with complicated stream communication like this!
One more thing, make sure you can just redirect this at the command prompt. Too often programmers try to do everything at the same time and get stuck:
./stdintest.py < input.txt
If it doesn't work there, it's not going to work in C#. Good luck

Categories