Win32Exception when using Process.Start() - c#

How Do I open google chrome using c#?
It shows System.ComponentModel.Win32Exception: 'The system cannot find the file specified'
I'd triedProcess.Start("C:\\Program Files(x86)\\Google\\Chrome\\Application\\chrome.exe"); too, but it shows the same exception
using System;
using System.Diagnostics;
namespace tempTest
{
class Program
{
static void Main(string[] args)
{
Process.Start("chrome.exe");
}
}
}

The chrome application path can be read from the registry.
You can try following codes:
var key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", false);
if(key != null)
{
var path = Path.Combine(key.GetValue("Path").ToString(), "chrome.exe");
if(File.Exists(path))
{
Process.Start(path);
}
}

Related

LeanFT Opening Browser in Incognito Mode

Problem: LeanFT in C# doesn't have a way to open the browser in incognito mode unfortunately. I am unable to add -incognito to path as I don't have admin rights. What can I do? I was thinking Sendkeys(ā€œ^+Nā€); but not sure how to do that via keyboard or if it would work as browser is already instantiated.
Has anyone else run into this problem? It's really cumbersome like I said since LeanFT doesn't allow incognito mode to be runned automatically.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using HP.LFT.SDK;
using HP.LFT.Verifications;
using System.Diagnostics;
using System.Threading;
using HP.LFT.SDK.Web;
using HP.LFT.Report;
using System.Drawing;
namespace Xpathtest
{
[TestClass]
public class LeanFtTest : UnitTestClassBase<LeanFtTest>
{
//The Browser object on which the test will be run
IBrowser browser;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
GlobalSetup(context);
}
[TestInitialize]
public void TestInitialize()
{
browser = BrowserFactory.Launch(BrowserType.Chrome);
}
[TestMethod]
public void TestMethod1()
{
try
{
// Navigate to Rally
browser.Navigate("-incognito https://rally1.rallydev.com/");
browser.Sync();
Thread.Sleep(3000);
browser.Refresh();
// Find Username edit box using Xpath
IEditField userName = browser.Describe<IEditField>(new EditFieldDescription
{
XPath = "//input[#id='j_username']"
});
userName.SetValue("TEST");
Thread.Sleep(3000);
// Find password edit box using Xpath
IEditField password = browser.Describe<IEditField>(new EditFieldDescription
{
XPath = "//input[#id='j_password']"
});
password.SetValue("TEST");
Thread.Sleep(3000);
IButton submit = browser.Describe<IButton>(new ButtonDescription
{
XPath = "//*[#id='login-button']"
});
submit.Click();
browser.FullScreen();
Image img = browser.GetSnapshot();
Reporter.ReportEvent("Screenshot of failure", "", Status.Passed, img);
Thread.Sleep(3000);
}
catch (Exception e)
{
Assert.Fail("Unexpected Error Occurred while= " + e.Message);
}
}
[TestCleanup]
public void TestCleanup()
{
browser.Close();
}
[ClassCleanup]
public static void ClassCleanup()
{
GlobalTearDown();
}
}
}
You should use process.Start to start Chrome, and browser.Attach to a description to attach to the opened browser.
Here's the idea roughly:
using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "chrome";
process.StartInfo.Arguments = "-incognito www.somesite.com";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
BrowserFactory.Attach(new BrowserDescription
{
Url = "www.somesite.com"
});
...
But as Motti said in the comments, Attach will not work without the LeanFT extension enabled - which is disabled in incognito

Getting 'The device is not ready' error when using DriveInfo.GetDrives()

i am trying to make a program that looks at all the drives, tries to find a removable one with the name "DOM WORK" and then gets the drive name (like E:) and then prints that. Unfortunately i get this error message:
Unhandled Exception: System.IO.IOException: The device is not ready.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIODriveError(String driveName, Int32 errorCode)
at System.IO.DriveInfo.get_VolumeLabel()
at WorkSync.Program.Main(String[] args) in d:\dominic\documents\visual studio 2015\Projects\WorkSync\WorkSync\Program.cs:line 19
I have tried building the program as an executable and then running it with administrator privileges, which did not work.
Here is my code that i am using:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkSync
{
class Program
{
static void Main(string[] args)
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
string memStickName = "";
foreach(DriveInfo drive in allDrives)
{
Console.WriteLine(drive.VolumeLabel);
if (drive.VolumeLabel == "DOM WORK" && drive.DriveType.ToString() == "removable")
{
memStickName = drive.Name;
break;
}
}
Console.WriteLine(memStickName);
}
}
}
You need to make sure that the drive is actually accessible using the DriveInfo.IsReady property.
foreach(DriveInfo drive in allDrives)
{
if (drive.IsReady == true)
{
// Check volume name here
}
}

TestStack.White and CCleaner

I've very new to the TestStack (White) UI Automation library and I'm having a bit of an issue in terms of "hooking" the process. I'm trying to hook CCleaner, but I keep getting
An unhandled exception of type 'TestStack.White.AutomationException'
occurred in TestStack.White.dll
Additional information: Couldn't find window with title Piriform
CCleaner in process 1156, after waiting for 30 seconds:
My current code is:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using TestStack.White;
using TestStack.White.Factory;
using TestStack.White.UIItems.Finders;
using TestStack.White.InputDevices;
using TestStack.White.UIItems.WindowItems;
namespace NightWipe
{
class Program
{
private const string ExeSourceFile = #"C:\Program Files\CCleaner\CCleaner.exe";
private static TestStack.White.Application _application;
private static TestStack.White.UIItems.WindowItems.Window _mainWindow;
static void Main(string[] args)
{
clean();
}
public static string clean()
{
var psi = new ProcessStartInfo(ExeSourceFile);
_application = TestStack.White.Application.AttachOrLaunch(psi);
_mainWindow = _application.GetWindow("Piriform CCleaner");
_mainWindow.WaitWhileBusy();
return "";
}
}
}
I thought that maybe it was the name of the process since CCleaner starts another process (not CCleaner.exe) but CCleaner64.exe as seen here, which I can assume is for 64 bit operating systems maybe? Anyway I tried names including: "CCleaner", "CCleaner64"; but this threw the same exact exception.
I'm using Inspect by Microsoft and this is what it pulls for me (large image):
Inspect's information. Any idea what I'm doing wrong here?
The problem is that CCleaner is visible as WIN32 app. So GetWindow() doesn't work. You can try this code:
public void CCleanerSample()
{
var application = Application.AttachOrLaunch(new ProcessStartInfo(#"C:\Program Files\CCleaner\CCleaner.exe"));
AutomationElement ccleanerAutomationElement = null;
Console.Write("Waiting till WIN32 app is launching");
while (ccleanerAutomationElement == null)
{
ccleanerAutomationElement = AutomationElement.RootElement.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.NameProperty, "Piriform CCleaner"));
Thread.Sleep(1000);
Console.Write(".");
}
Console.WriteLine(" Done");
var mainWindow = new Win32Window(ccleanerAutomationElement, WindowFactory.Desktop, InitializeOption.NoCache,
new WindowSession(application.ApplicationSession, InitializeOption.NoCache));
}

Process.Start("IExplore.exe", "http://google.com") Not Launching On VM. Works on Server and Local

As Above in Title
Process.Start("IExplore.exe", "http://google.com")
Does not launch IE on a VM I am using. However Executing on a server real machine and local machine it launches correctly.
Tried the following:
Process.Start("IEXPLORE.EXE", "-nomerge http://google.com/");
as suggested in post Process.Start("IEXPLORE.EXE") immediately fires the Exited event after launch.. why?
and
try
{
Process.Start("http://google.com");
}
catch (System.ComponentModel.Win32Exception)
{
Process.Start("IExplore.exe", "http://google.com");
}
and
ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
Any suggestions greatly appreciated
You got IE installed on the VM right :D? Anyway try running the app as administrator mayby the UAC settings are "wrong" on the VM.
Try this...
Process.Start("http://www.google.com");
It will launch the site with your default browser. Assuming that's Internet Explorer, you're good to go.
Here is a stripped down class that you might find useful if you want to do IE automation.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using SHDocVw;
using mshtml;
public class InternetExplorerInstance
{
public InternetExplorer Instance;
public static InternetExplorerInstance GetCurrentInternetExplorerInstance()
{
InternetExplorer currentInternetExplorer = CurrentInternetExplorer();
if ( currentInternetExplorer != null )
{
return new InternetExplorerInstance( currentInternetExplorer );
}
return null;
}
private InternetExplorerInstance( InternetExplorer ie )
{
Instance = ie;
}
public static void Iterate()
{
GetInternetExplorers();
}
private static IEnumerable<InternetExplorer> GetInternetExplorers()
{
ShellWindows shellWindows = new ShellWindowsClass();
List<InternetExplorer> allExplorers = shellWindows.Cast<InternetExplorer>().ToList();
IEnumerable<InternetExplorer> internetExplorers = allExplorers.Where( ie => Path.GetFileNameWithoutExtension( ie.FullName ).ToLower() == "iexplore" );
return internetExplorers;
}
public static void LaunchNewPage( string url )
{
InternetExplorer internetExplorer = GetInternetExplorers().FirstOrDefault();
if ( internetExplorer != null )
{
internetExplorer.Navigate2( url, 0x800 );
WindowsApi.BringWindowToFront( (IntPtr) internetExplorer.HWND );
}
else
{
internetExplorer = new InternetExplorer();
internetExplorer.Visible = true;
internetExplorer.Navigate2( url );
WindowsApi.BringWindowToFront((IntPtr) internetExplorer.HWND);
}
}
}
Not all code is included, but it should be enough for a start.

Opening mp3 by not-default program C sharp

How can I open mp3 file with RealPlayer while the default is MediaPlayer
I know Process and ProcessStartInfo method, but I would like to know how to "open program with..."
Can you help me, plz?
Okay, so thought I'd make this possible for you before I clock off for the night. I have thrown together a working console application which loads (known) installed programs from the registry's App Path key. The solution is far from perfect, won't be the safest, fastest, or most reliable solution, and it certainly shouldn't be seen amongst any production code, but it is more than enough to aid you, hopefully, in developing what it is you need:
So, here is the code, minus the namespace...
using System;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
if (args.Length >= 0 && !string.IsNullOrEmpty(args[0]) && File.Exists(args[0]))
{
var programs = new InstalledPrograms();
var programKey = "RealPlay.exe".ToLowerInvariant();
if (programs.ContainsKey(programKey))
{
var programPath = programs[programKey];
if (!string.IsNullOrEmpty(programPath) && File.Exists(programPath))
{
var process = new Process();
process.StartInfo = new ProcessStartInfo(programPath);
process.StartInfo.Arguments = args[0];
if (process.Start())
{
Console.WriteLine("That was easy!");
}
else
{
Console.WriteLine("Hell's bells and buckets of blood, we seem to have hit a snag!");
}
}
}
}
else
{
Console.WriteLine("Specify a file as an argument, silly!");
}
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
class InstalledPrograms : Dictionary<string, string>
{
static string PathKeyName = "Path";
static string RegistryKeyToAppPaths = #"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";
public InstalledPrograms()
{
Refresh();
}
public void Refresh()
{
Clear();
using (var registryKey = Registry.LocalMachine.OpenSubKey(RegistryKeyToAppPaths))
{
var executableFullPath = string.Empty;
foreach (var registrySubKeyName in registryKey.GetSubKeyNames())
{
using (var registrySubKey = registryKey.OpenSubKey(registrySubKeyName))
{
executableFullPath = registrySubKey.GetValue(string.Empty) as string;
Add(registrySubKeyName.ToLowerInvariant(), executableFullPath);
}
}
}
}
}
}
Though we check for file existence, and other minor but necessary checks are made, you would still need to tighten this up further when plugged into the environment of your own code, including, among other things, exception handling for, but not limited to, registry access issues.

Categories