how to find the execution path of a installed software - c#

How can i find the execution path of a installed software in c# for eg media player ,vlc player . i just need to find their execution path . if i have a vlc player installed in my D drive . how do i find the path of the VLC.exe from my c# coding

Using C# code you can find the path for some excutables this way:
private const string keyBase = #"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";
private string GetPathForExe(string fileName)
{
RegistryKey localMachine = Registry.LocalMachine;
RegistryKey fileKey = localMachine.OpenSubKey(string.Format(#"{0}\{1}", keyBase, fileName));
object result = null;
if (fileKey != null)
{
result = fileKey.GetValue(string.Empty);
fileKey.Close();
}
return (string)result;
}
Use it like so:
string pathToExe = GetPathForExe("wmplayer.exe");
However, it may very well be that the application that you want does not have an App Paths key.

This method works for any executable located in a folder which is defined in the windows PATH variable:
private string LocateEXE(String filename)
{
String path = Environment.GetEnvironmentVariable("path");
String[] folders = path.Split(';');
foreach (String folder in folders)
{
if (File.Exists(folder + filename))
{
return folder + filename;
}
else if (File.Exists(folder + "\\" + filename))
{
return folder + "\\" + filename;
}
}
return String.Empty;
}
Then use it as follows:
string pathToExe = LocateEXE("example.exe");
Like Fredrik's method it only finds paths for some executables

I used the CurrentVersion\Installer\Folders registry key. Just pass in the product name.
private string GetAppPath(string productName)
{
const string foldersPath = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\Folders";
var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
var subKey = baseKey.OpenSubKey(foldersPath);
if (subKey == null)
{
baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
subKey = baseKey.OpenSubKey(foldersPath);
}
return subKey != null ? subKey.GetValueNames().FirstOrDefault(kv => kv.Contains(productName)) : "ERROR";
}

None of the answers worked for me. After hours of searching online, I was able to successfully get the installation path. Here is the final code.
public static string checkInstalled(string findByName)
{
string displayName;
string InstallPath;
string registryKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
//64 bits computer
RegistryKey key64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey key = key64.OpenSubKey(registryKey);
if (key != null)
{
foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
{
displayName = subkey.GetValue("DisplayName") as string;
if (displayName != null && displayName.Contains(findByName))
{
InstallPath = subkey.GetValue("InstallLocation").ToString();
return InstallPath; //or displayName
}
}
key.Close();
}
return null;
}
you can call this method like this
string JavaPath = Software.checkInstalled("Java(TM) SE Development Kit");
and boom. Cheers

Have a look at MsiEnumProductsEx

This stackoverflow.com article describes how to get the application associated with a particular file extension.
Perhaps you could use this technique to get the application associated with certain extensions, such as avi or wmv - either Medial Player or in your case VLC player?

Related

C# Copy file from Android to PC

I need to copy a bunch of files from an Android phone to the PC.
It doesn't work the normal way, the PC is super slow and crashes all the time for some reason.
I want to copy it file by file.
My problem is that if I use Directory.GetFiles("Path") or DirectoryInfo.GetFiles("Path") it does add the persistant Datapath to the path for some reason and I get this error message:
DirectoryNotFoundException: Could not find a part of the path 'D:\GameDev\CopyProgram\Dieser PC\HTC One M9\Interner gemeinsamer Speicher'.
The actual path is only "Dieser PC\HTC One M9\Interner gemeinsamer Speicher", is there any way to do that?
//there is an input field where you can enter the paths
(copy it from the explorer)
[SerializeField]
private string copyFrom = "Dieser PC\HTC One M9\Interner gemeinsamer Speicher";
[SerializeField]
private string copyTo = "C:\Users\Nutzer\Desktop\Neuer Ordner";
private bool running = false;
public void Copy()
{
if(running == true)
{
return;
}
running = true;
//Start
//Get all items from folder
DirectoryInfo d = new DirectoryInfo(copyFrom);
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
string currentFile = file.DirectoryName + "/" + file.Name;
string copyFile = copyTo + "/" + file.Name;
try
{
if (file == null)
continue;
File.Copy(currentFile, copyFile, true);
}
catch (Exception)
{
throw;
}
}
//End
running = false;
}
I searched through the internet and could not find a solution, please help!
Thanks!

Accessing USB Drives from 'Computer'

I'm trying to copy files over from the desktop to a USB drive programmatically. However, when trying to run this code, I am geting an error stating that part of the path could not be found:
if (dr == DialogResult.Yes)
{
string selected = comboBox1.GetItemText(comboBox1.SelectedItem);
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filefolder = #"\UpgradeFiles";
string fileLocation = filePath + filefolder;
if (!Directory.Exists(fileLocation))
{
Directory.CreateDirectory(fileLocation);
}
else if (Directory.Exists(fileLocation))
{
DirectoryInfo di = new DirectoryInfo(fileLocation);
FileInfo[] fileList = di.GetFiles();
foreach (FileInfo file in fileList)
{
string DrivePath = Environment.GetFolderPath(
Environment.SpecialFolder.MyComputer);
string CopyToDrive = comboBox1.Text;
file.CopyTo(DrivePath + CopyToDrive, false);
}
}
}
The combobox contains the selected drive letter. Am I approaching this wrong when trying to add "computer\driveletter"?
Your File.CopyTo(DrivePath + CopyToDrive, false) should be:
File.CopyTo(CopyToDrive + File.Name, false);
but with a bit of syntactic sugar like using Path.Combine or String.Format instead of just "+".
The issue is that File.CopyTo requires both the directory AND filename of the end location, when you're just providing the directory. This can be seen in the documentation for the method call here: https://msdn.microsoft.com/en-us/library/f0e105zt(v=vs.110).aspx

Getting blank InstallDate for few installed softwares, even if date is there in registry

I am using below code to get list of installed software, i am able to get installation date for around 90% software but for around 10% software, i am getting blank in installation date (even though the installdate is present in their registry key)
key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
foreach (String keyName in key.GetSubKeyNames())
{
RegistryKey subkey = key.OpenSubKey(keyName);
string appname = subkey.GetValue("DisplayName") as string;
string Vendor_Publisher = Convert.ToString(subkey.GetValue("Publisher"));
string Version = Convert.ToString(subkey.GetValue("DisplayVersion"));
string InstallDate = Convert.ToString(subkey.GetValue("InstallDate"));
}
The application is installed on windows 7 (32-bit)
What i have found that... All keys may not be present for all entry in the registry. So my suggestion is to check whether that key is present or not :
You can registry entry with `subkey.GetValueNames():
string registry_key = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
RegistryKey subkey = null;
try
{
foreach (string subkey_name in key.GetSubKeyNames())
{
subkey = key.OpenSubKey(subkey_name);
string[] columns = subkey.GetValueNames();
string appname = subkey.GetValue("DisplayName") as string;
string Vendor_Publisher = Convert.ToString(subkey.GetValue("Publisher"));
string Version = Convert.ToString(subkey.GetValue("DisplayVersion"));
if (columns.Contains("InstallDate"))
{
string InstallDate = Convert.ToString(subkey.GetValue("InstallDate"));
}
}
}
catch (Exception ex)
{
throw ex;
}
}
You can put the check for all the entries you are reading.

Get target of shortcut folder

How do you get the directory target of a shortcut folder? I've search everywhere and only finds target of shortcut file.
I think you will need to use COM and add a reference to "Microsoft Shell Control And Automation", as described in this blog post:
Here's an example using the code provided there:
namespace Shortcut
{
using System;
using System.Diagnostics;
using System.IO;
using Shell32;
class Program
{
public static string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell shell = new Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return string.Empty;
}
static void Main(string[] args)
{
const string path = #"C:\link to foobar.lnk";
Console.WriteLine(GetShortcutTargetFile(path));
}
}
}
In windows 10 it needs to be done like this, first add COM reference to "Microsoft Shell Control And Automation"
// new way for windows 10
string targetname;
string pathOnly = System.IO.Path.GetDirectoryName(LnkFileName);
string filenameOnly = System.IO.Path.GetFileName(LnkFileName);
Shell shell = new Shell();
Shell32.Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null) {
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
targetname = link.Target.Path; // <-- main difference
if (targetname.StartsWith("{")) { // it is prefixed with {54A35DE2-guid-for-program-files-x86-QZ32BP4}
int endguid = targetname.IndexOf("}");
if (endguid > 0) {
targetname = "C:\\program files (x86)" + targetname.Substring(endguid + 1);
}
}
If you don't want to use dependencies you can use https://blez.wordpress.com/2013/02/18/get-file-shortcuts-target-with-c/
But lnk format is undocumented, so do it only if you understand risks.
An even simpler way to get the linked path that I use is:
private static string LnkToFile(string fileLink)
{
string link = File.ReadAllText(fileLink);
int i1 = link.IndexOf("DATA\0");
if (i1 < 0)
return null;
i1 += 5;
int i2 = link.IndexOf("\0", i1);
if (i2 < 0)
return link.Substring(i1);
else
return link.Substring(i1, i2 - i1);
}
But it will of course break if the lnk-file format changes.
public static string GetLnkTarget(string lnkPath)
{
var shl = new Shell();
var dir = shl.NameSpace(Path.GetDirectoryName(lnkPath));
var itm = dir.Items().Item(Path.GetFileName(lnkPath));
var lnk = (ShellLinkObject)itm.GetLink;
if (!File.Exists(lnk.Path)){
return lnk.Path.Replace("Program Files (x86)", "Program Files");
}
else{
return lnk.Path;
}
}
if you want find your application path that has shortcut on desktop, an easy way that i use, is the following:
Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\")
this code return any exe path that is running,Regardless that who requested file
Thanks to Mohsen.Sharify's answer I got more neat piece of code:
var fileName = Process.GetCurrentProcess().MainModule.FileName;
var folderName = Path.Combine(fileName, ".."); //origin folder
All file shortcuts have a .lnk file extension you can check for. Using a string for example, you could use string.EndsWith(".lnk") as a filter.
All URL shortcuts have a .url file extension, so you will need to account for those as well if needed.

how to check if OpenOffice is installed programatically using c#

how to check if OpenOffice is installed programatically using c#
public bool isOpenofficeInstalled()
{
//The registry key:
string SoftwareKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(SoftwareKey))
{
bool flag = false;
//Let's go through the registry keys and get the info we need:
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
//If the key has value, continue, if not, skip it:
// if (((sk.GetValue("DisplayName")).ToString() == "OpenOffice.org 3.2"))
if((sk.GetValue("DisplayName")).ToString() == "OpenOffice.org 3.2")
{
flag = true;
////install location ?
//if (sk.GetValue("InstallLocation") == null)
// Software += sk.GetValue("DisplayName") + " - Install path not known\n"; //Nope, not here.
//else
// Software += sk.GetValue("DisplayName") + " - " + sk.GetValue("InstallLocation") + "\n"; //Yes, here it is...
}
}
catch (Exception)
{
}
}
}
return flag;
}
}
Here is a solution that gets the startup location of the default program to open a odt file. As long as the file association has not been changed this works regardless of what version is installed.
(this is VB.NET)
Dim odt = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(".odt")
Dim linkedValue = odt.GetValue("")
Dim linkedKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(linkedValue)
Dim openWith = linkedKey.OpenSubKey("Shell\Open\Command").GetValue("")
Dim O As String = CStr(openWith)
If O.Contains("swriter.exe") Then
// proceed with code
Else
// error message
End If
Same as in any other language? Search the known locations on the file system for the executable that launches open office? Check for libraries? Parse the output of "which openoffice"?
There are lots of options, and I'd say that most of them would not be reliable.

Categories