I have the following code below. I can't seem to get it to work for adding a folder to favorites. If I change it to specialfolders.desktop, it creates a shortcut on the desktop.
private void buttonAddFav_Click(object sender, EventArgs e)
{
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string targetPath = listFolderResults.SelectedItem.ToString();
var wsh = new IWshShell_Class();
IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
Environment.GetFolderPath(Environment.SpecialFolder.Favorites) + "\\shorcut2.lnk") as IWshRuntimeLibrary.IWshShortcut;
shortcut.TargetPath = targetPath;
shortcut.Save();
}
Environment.SpecialFolder.Favorites represents the folder that contains your Internet Explorer favorites, which are located in the %USERPROFILE%\Favorites folder.
There is no Environment.SpecialFolder value that represents your Windows Explorer favorites, which are located in the %USERPROFILE%\Links folder.
To retrieve the path to the Links folder, you will have to query the Shell directly for the FOLDERID_Links path using either:
PInvoke to call SHKnownFolderPath().
COM interop to call IKnownFolderManager.GetFolder() and then IKnownFolder.GetPath().
The below code ended up working for me. The answers below were helpful in figuring out I need to build around the %userprofile%\links, but %userprofile% gave me errors when saving. When I used the method below, it worked.
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string targetPath = listFolderResults.SelectedItem.ToString();
string shortcutPath = string.Format(#"C:\Users\{0}\Links",Environment.UserName);
MessageBox.Show(shortcutPath);
var wsh = new IWshShell_Class();
IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
shortcutPath + string.Format(#"\{0}.lnk",textFavName.Text)) as IWshRuntimeLibrary.IWshShortcut;
shortcut.TargetPath = targetPath;
shortcut.Save();
Related
I'm trying t create a shortcut in using the IWshShortcut and WshShell. My exe - for which I'm creating the shortcut has two dots in the file name.
Here is what I'm doing:
string link = Path.Combine(TargetPath, Path.GetFileName(FileName) ?? FileName);
link = Path.ChangeExtension(link, string.Concat(Path.GetExtension(link), ShortcutExtensionString));
var shell = new WshShell();
var shortcut = shell.CreateShortcut(link) as IWshShortcut;
shortcut.Description = Description;
shortcut.Arguments = string.Join(" ", Parameters);
shortcut.TargetPath = Path.Combine(WorkingDirectory, "CompanyName.ApplicationName.exe");
shortcut.WorkingDirectory = string.IsNullOrWhiteSpace(WorkingDirectory)
? TargetPath
: WorkingDirectory;
//save the shortcut.
shortcut.Save();
With this, the code gets executed well, but the target path in the desktop shortcut comes truncated for the exe name like this: "E:\OSO\App\bin\CompanyName.exe"
The whole thing happens from a laptop to create the shortcut in a remote server. I use WNetAddConnection2 to connect to the desktop directory of the server for the logged on user (providing the username and pwd for the admin user).
It appears to work fine for the local laptop though.
How can I solve this?
Try adding the target path as below,
shortcut.TargetPath = WorkingDirectory + #"\CompanyName.ApplicationName.exe";
I am building a custom installer. How can I create a shortcut to an executable in the start menu? This is what I've come up with so far:
string pathToExe = #"C:\Program Files (x86)\TestApp\TestApp.exe";
string commonStartMenuPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu);
string appStartMenuPath = Path.Combine(commonStartMenuPath, "Programs", "TestApp");
// TODO: create shortcut in appStartMenuPath
I'm targeting Windows 7.
Using the Windows Script Host (make sure to add a reference to the Windows Script Host Object Model, under References > COM tab):
using IWshRuntimeLibrary;
private static void AddShortcut()
{
string pathToExe = #"C:\Program Files (x86)\TestApp\TestApp.exe";
string commonStartMenuPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu);
string appStartMenuPath = Path.Combine(commonStartMenuPath, "Programs", "TestApp");
if (!Directory.Exists(appStartMenuPath))
Directory.CreateDirectory(appStartMenuPath);
string shortcutLocation = Path.Combine(appStartMenuPath, "Shortcut to Test App" + ".lnk");
WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutLocation);
shortcut.Description = "Test App Description";
//shortcut.IconLocation = #"C:\Program Files (x86)\TestApp\TestApp.ico"; //uncomment to set the icon of the shortcut
shortcut.TargetPath = pathToExe;
shortcut.Save();
}
By MSI setup, you can easily create Start Menu Shortcut for your application. But when it comes to custom installer setup, you need to write custom code to create All Programs shortcut. In C#, you can create shortcut using Windows Script Host library.
Note: To use Windows Script Host library, you need to add a reference under References > COM tab > Windows Script Host Object Model.
See this article for more info: http://www.morgantechspace.com/2015/01/create-start-menu-shortcut-all-programs-csharp.html
Create shortcut only for Current User:
string programs_path = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
string shortcutFolder = Path.Combine(programs_path, #"YourAppFolder\SampleApp");
if (!Directory.Exists(shortcutFolder))
{
Directory.CreateDirectory(shortcutFolder);
}
WshShellClass shellClass = new WshShellClass();
string settingsLink = Path.Combine(shortcutFolder, "Settings.lnk");
IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
shortcut.TargetPath = #"C:\Program Files\YourAppFolder\MyAppSettings.exe";
shortcut.IconLocation = #"C:\Program Files\YourAppFolder\settings.ico";
shortcut.Arguments = "arg1 arg2";
shortcut.Description = "Click to edit SampleApp settings";
shortcut.Save();
Create Shortcut for All Users:
You can get common profile path for All Users by using API function SHGetSpecialFolderPath.
using IWshRuntimeLibrary;
using System.Runtime.InteropServices;
---------------------------------
[DllImport("shell32.dll")]
static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, bool fCreate);
const int CSIDL_COMMON_STARTMENU = 0x16;
public static void CreateShortcutForAllUsers()
{
StringBuilder allUserProfile = new StringBuilder(260);
SHGetSpecialFolderPath(IntPtr.Zero, allUserProfile, CSIDL_COMMON_STARTMENU, false);
//The above API call returns: C:\ProgramData\Microsoft\Windows\Start Menu
string programs_path = Path.Combine(allUserProfile.ToString(), "Programs");
string shortcutFolder = Path.Combine(programs_path, #"YourAppFolder\SampleApp");
if (!Directory.Exists(shortcutFolder))
{
Directory.CreateDirectory(shortcutFolder);
}
WshShellClass shellClass = new WshShellClass();
//Create Shortcut for Application Settings
string settingsLink = Path.Combine(shortcutFolder, "Settings.lnk");
IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
shortcut.TargetPath = #"C:\Program Files\YourAppFolder\MyAppSettings.exe";
shortcut.IconLocation = #"C:\Program Files\YourAppFolder\settings.ico";
shortcut.Arguments = "arg1 arg2";
shortcut.Description = "Click to edit SampleApp settings";
shortcut.Save();
}
This is pretty much the same as this question: Create shortcut on desktop C#.
To copy from that answer, you'll need to create the shortcut file yourself.
using (StreamWriter writer = new StreamWriter(appStartMenuPath + ".url"))
{
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + pathToExe);
writer.WriteLine("IconIndex=0");
string icon = pathToExe.Replace('\\', '/');
writer.WriteLine("IconFile=" + icon);
}
This code is untested, of course, but it was accepted on that other question and it looks right.
I see another answer on that question that lists how to do it with the Windows API and some COM interop, but I'd be tempted to shy away from that and just use the above code if it works. It's more personal preference than anything, and I'd normally be all for using a pre-established API for this, but when the solution is this simple I'm just not sure how worth it that option really is. But for good measure, I believe this code should work. Again, of course, it's totally untested. And especially here where you're playing with things like this, make sure you understand each line before you execute it. I'd hate to see you mess up something on your system because of a blind following to code I posted.
WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(appStartMenuPath + ".lnk");
shortcut.Description = "Shortcut for TestApp";
shortcut.TargetPath = pathToExe;
shortcut.Save();
You will, of course, also need a reference to the "Windows Script Host Object Model," which can be found under "Add a Reference" then "COM."
the project i am working on has to run on the windows startup i found the code, but what if the user don't wan't it to start on the startup!, do i have to tell the user to search for the sortcut and delete it, or simply make a button for that option, i know how to delete the file like this:
if(File.Exists(#"C:\Users\Maged\Desktop\remainder\WindowsFormsApplication1\bin\Debug\WindowsFormsApplication1.exe"))
{
File.Delete(#"C:\Users\Maged\Desktop\remainder\WindowsFormsApplication1\bin\Debug\WindowsFormsApplication1.exe");
}
i need to make the program searsh for MyStartupShortcut.lnk and delete it if exists.
here is my code on creating the shortcut:
void CreateStartupShortcut()
{
string startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
WshShell shell = new WshShell();
string shortcutAddress = startupFolder + #"\MyStartupShortcut.lnk";
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "A startup shortcut. If you delete this shortcut from your computer, LaunchOnStartup.exe will not launch on Windows Startup";
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.TargetPath = Application.ExecutablePath;
shortcut.Save();
}
i need to delete this file no matter the director is, any help?
Using shortcutAddress created as in the CreateStartupShortcut method the deletion of the shortcut should be achieved with the code:
if ( File.Exists(shortcutAddress) )
{
File.Delete(shortcutAddress );
}
How can I create a shortcut of power options with C# code?
This is my code:
WshShellClass wshShell = new WshShellClass();
IWshRuntimeLibrary.IWshShortcut MyShortcut;
MyShortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(#"C:\user\Administrator\power options.lnk");
MyShortcut.TargetPath = ???????;
MyShortcut.IconLocation = Application.StartupPath + ??????;
MyShortcut.Save();
Building on the answer from Moo-Juice, try the following:
WshShell shell = new WshShell();
string app = Path.Combine(Environment.SystemDirectory, "powercfg.cpl");
string linkPath = #"C:\PowerLink.lnk";
IWshShortcut link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkPath);
link.TargetPath = app;
link.IconLocation = string.Format("{0},2", app);
link.Save();
The items in the control panel are stored in C:\windows\system32 with a .cpl extension. Therefore your target, for power options, should be:
C:\windows\system32\powercfg.cpl
Note: Do not use the hard-coded strings I have used here, use Environment.SystemDirectory to locate the directory appropriately.
I wanted to give my user an option for "Start with Windows". When user check this option it will place a shortcut icon into Startup folder (not in registry).
On Windows restart, it will load my app automatically.
How can this be done?
you can use the Enviroment.SpecialFolder enum, although depending on your requirements you might look at creating a windows service instead of an app that has to start on startup.
File.Copy("shortcut path...", Environment.GetFolderPath(Environment.SpecialFolder.Startup) + shorcutname);
edit:
File.Copy needs an origin file directory-path and the target directory-path to copy a file. The key in that snippet is Enviroment.GetFolderPath(Enviroment.SpecialFolder.Startup) which is getting the startup folder path where you want to copy your file to.
you could use the above code several ways. In case you've got an installer project for your app, you could run something like this on install. Another way could be when the app launches it checks if the shorcut exists there and puts one there if not (File.Exists()).
Here is a question about creating shortcuts in code also.
WshShell wshShell = new WshShell();
IWshRuntimeLibrary.IWshShortcut shortcut;
string startUpFolderPath =
Environment.GetFolderPath(Environment.SpecialFolder.Startup);
// Create the shortcut
shortcut =
(IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(
startUpFolderPath + "\\" +
Application.ProductName + ".lnk");
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Description = "Launch My Application";
// shortcut.IconLocation = Application.StartupPath + #"\App.ico";
shortcut.Save();
private void button2_Click(object sender, EventArgs e)
{
string pas = Application.StartupPath;
string sourcePath = pas;
string destinationPath = #"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup";
string sourceFileName = "filename.txt";//eny tipe of file
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}