Find default email client - c#

Using C#, how can I determine which program is registered as the default email client? I don't need to launch the app, I just want to know what it is.

Use the Registry class to search the registry. This console app demonstrates the principle.
using System;
using Microsoft.Win32;
namespace RegistryTestApp
{
class Program
{
static void Main(string[] args)
{
object mailClient = Registry.GetValue(#"HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail", "", "none");
Console.WriteLine(mailClient.ToString());
}
}
}

You can look in the registry on the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail

You can read this registry key from
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail

Default email client depends on the user. HKLM lists all registered email clients; the first one returned may not be the current user's default. Better to read HKEY_CURRENT_USER\Software\Clients\Mail.
Also this only gives you the name of the email application. If you want its executable file name, you have to go on with something like:
object mailCommand = Registry.GetValue(#"HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail\" + mailClient.ToString() + #"\shell\open\command", "", "none");
and then remove anything extraneous from the command-line string that you don't need (quotes, parameters).

I think you should be able to find that info in the registry at HKLM\Software\Clients\Mail.
Look for the default string value.

Related

How to make a registry entry using C# cake?

I need to create a registry entry based on finding of 32/64-bit system from cake script. I can see the File operations reference, Directory operations reference in C# cake site. But i could not find the registry related reference in C# cake. Could anyone please let me know is there any option to make a registry entry using C# cake? If so, please specify the reference link. This will help me a lot to continue in cake script.
An alternative to using C# you could also be using the Reg.exe shipped with all major versions of Windows.
You could use this tool with Cake using StartProcess alias.
An example of doing this below:
DirectoryPath system32Path = Context.Environment
.GetSpecialPath(SpecialPath.Windows)
.Combine("System32");
FilePath regPath = system32Path.CombineWithFilePath("reg.exe");
string keyName = "HKEY_CURRENT_USER\\Software\\Cake";
string valueName = "Rocks";
string valueData = "1";
ProcessSettings regSettings = new ProcessSettings()
.WithArguments(
arguments => arguments
.Append("add")
.AppendQuoted(keyName)
.Append("/f")
.AppendSwitchQuoted("/v", valueName)
.AppendSwitchQuoted("/t", "REG_DWORD")
.AppendSwitchQuoted("/d", valueData)
);
int result = StartProcess(regPath, regSettings);
if (result == 0)
{
Information("Registry value successfully set");
}
else
{
Information("Failed to set registry value");
}
Currently, there are no Cake aliases for working with the registry. Having said that, there is nothing to stop you manipulating the Registry directly using that standard C# types.
An example of one such approach is here:
Writing to registry in a C# application
Cake provides a number of aliases for things that are more complicated to do, however, remember that almost everything that is provided in an alias could be done directly with C# in your main script. The aliases are simply there as a convenience.

how to make exe file work on one computer only

I wrote a program using C# and make exe file using advanced installer and it work good but i want to make this exe file work in one computer, because some clints
take exe and give this exe to another and i want to privint that and protect my works
run the code below on the machine that you want your .exe. file to work on (it will give you this machines MAC address).
2. Add this MAC address to the code below
3. Add the code below to your C# code to ensure that it only runs on the machine with the correct MAC address (unique)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace OneMachine
{
class Program
{
static void Main(string[] args)
{
string clientMAC = "XX-XX-XX-XX-XX-XX"; // put the correct value here when you know it
string thisComputerMAC = GetMACAddress2();
Console.WriteLine("MAC:" + thisComputerMAC); // remove this when necessary
if (clientMAC == thisComputerMAC)
{
Console.WriteLine("this is the right computer");
} else
{
Console.WriteLine("PROGRAM WONT RUN ON THIS COMPUTER");
}
}
public static string GetMACAddress2()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
//IPInterfaceProperties properties = adapter.GetIPProperties(); Line is not required
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
} return sMacAddress;
}
}
}
reference: C# Get Computer's MAC address "OFFLINE"
I think what you want would be some sort of licence key and an authorization method.
A quick google turned up this article which you may find useful.
http://www.codeproject.com/Articles/28678/Generating-Unique-Key-Finger-Print-for-a-Computer
u can create the security constrain for exe like
by Giving unique password
By Entering the serial Key i.e. Licence Key which will know to u only or create random serial key generator based on the system.
You can allow only one user run your program by using a hardware ID to identify the user using the application or you can use a licensing system.

DefaultBrowser from Registry doesn't work

I'm trying to open a url in the default browser. Obviously I thought that Shell Exec will open it in the default browser but it doesn't.
Then I tried explicit:
Process.Start(GetDefaultBrowserPath(), "http://stackoverflow.com");
private static string GetDefaultBrowserPath()
{
string key = #"htmlfile\shell\open\command";
RegistryKey registryKey =
Registry.ClassesRoot.OpenSubKey(key, false);
// get default browser path
return ((string)registryKey.GetValue(null, null)).Split('"')[1];
}
It always returns Internet Explorer but not my default which is Firefox. I tried it on several computers...
I don't care which way to call the link in the default browser, but it has to be the default
Have you tried just running:
Process.Start("http://stackoverflow.com");
My test application (below) opens the site in my default browser:
using System;
using System.Diagnostics;
namespace ProcessStartSample
{
class Program
{
static void Main(string[] args)
{
Process.Start("http://stackoverflow.com");
}
}
}
In other words, let the operating system do the heavy work of working out what the users default browser is for you! =)
Just Try this :)
Process.Start("http://stackoverflow.com");
And if you want to find your default browser you should open HKEY_CLASSES_ROOT\http\shell\open\command\default key.
Please pay attention "http" not "htmlFile"
EDIT:
CODE:
RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(#"http\shell\open\command", false);
string value = registryKey.GetValue("").ToString();
Windows will start the default browser on the user's system for you automatically if you just specify the URL to open:
Process.Start("http://www.google.com/");
No need for any fancy Registry trickery, unless you are trying to ascertain which browser is set as the default.

How can I get another application's installation path programmatically?

I'd like to know where the installation path for an application is. I know it usually is in ...\Program Files... but I guess some people install it in different locations. I do know the name of the application.
Thank you.
The ideal way to find a program's installation path (on Windows) is to read it from the registry. Most installers will create a registry key for that program that contains the installation path. Exactly where this key is and what it will be named varies depending on the program in question.
To find if the program has a key in the registry, open 'regedit' and use the Edit > Find option to try and locate a key with the program name. If such a key exists, you can read it using the RegistryKey class in the .NET Framework library.
If the program does not have a registry key then another option is just to ask the user to locate the .exe file with the OpenFileDialog, although this is obviously not ideal.
Many (most?) programs create an App Paths registry key. Have a look at
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
If you know the application in question (as compared to any application) registry key is the probably the best option (if one exists).
The install might put in its own custom "install path key" somewhere (so do a find as Fara mentioned) or it might be in the uninstall section for installed programs, so you could check:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
But be aware that any new version of an install could change the key it writes out, both for a custom key or for the uninstall entry. So checking the registry should probably be only for a known install\version.
tep
Best way is to use Installer APIs to find the program location.
You can write a Managed wrapper over the APIs
Search for MsiGetProductInfo
Reference: http://msdn.microsoft.com/en-us/library/aa369558(VS.85).aspx
You can use MSI (I wrote a C# wrapper for it here https://github.com/alialavia/MSINet). Here is a simple example:
var location = "";
foreach (var p in InstalledProduct.Enumerate())
{
try
{
if (p.InstalledProductName.Contains("AppName"))
{
location = p.InstallLocation;
break;
}
}
catch { }
}
Take a look in the registry.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\
or
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\
Each of the above contain a list of sub-keys, one for each installed application (as it appears, for example, in the "Programs and Features" applet)
You can search for your application there, or if you know the product code, access it directly.
public string GetInstallPath(string applicationName)
{
var installPath = FindApplicationPath(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", applicationName);
if (installPath == null)
{
installPath = FindApplicationPath(#"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", applicationName);
}
return installPath;
}
private string FindApplicationPath(string keyPath, string applicationName)
{
var hklm = Registry.LocalMachine;
var uninstall = hklm.OpenSubKey(keyPath);
foreach (var productSubKey in uninstall.GetSubKeyNames())
{
var product = uninstall.OpenSubKey(productSubKey);
var displayName = product.GetValue("DisplayName");
if (displayName != null && displayName.ToString() == applicationName)
{
return product.GetValue("InstallLocation").ToString();
}
}
return null;
}

How to change application settings (Settings) while app is open?

I've written a class that should allow me to easily read and write values in app settings:
public static class SettingsManager
{
public static string ComplexValidationsString
{
get { return (string)Properties.Settings.Default["ComplexValidations"]; }
set
{
Properties.Settings.Default["ComplexValidations"] = value;
Properties.Settings.Default.Save();
}
}
the problem is the value isn't really saved, I mean it is not changed when I exit the application and run it again. What can I do to ensure that the saved value persists between closing and opening again?
settings scope must be user not application
You should check
Properties.Settings.Default.Properties["ComplexValidations"].IsReadOnly
It is probably true, this is what Roland means with "Application Scope". Save will fail silently. Take a look at Project|Properties|Settings, 3rd column.
Are you sure it's not saving the changes? The [ProgramName].exe.config file in the bin folder won't be updated. The acutal file used is usually put in C:\Documents and Settings\[user]\Local Settings\Application Data\[company name]\[application].exe[hash string]\[version]\user.config. I know when I tried this kind of thing it took me a while to realise this was the file that was getting updated.
I just tested a User Setting and it is persisted if you run this Console app twice:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Settings1.Default.Setting);
Console.ReadLine();
Settings1.Default.Setting = "A value different from app.config's";
Settings1.Default.Save();
}
}
Just try it out. It won't take a minute.

Categories