How to start a Process from a Win 8 App? - c#

I can’t find System.Diagnostics.Process to start a new process. I guess this is on purpose. But is there a other way? Is this even possible?

You can use this reference on Windows 8 Metro application : How to Start a external Program from Metro App.
All the Metro-style applications work in the highly sand boxed environment and there is no way to directly start an external application.
You can try using Launcher class
Launcher.LaunchFileAsync
// Path to the file in the app package to launch
string exeFile = #"C:\Program Files (x86)\App.exe";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation
.GetFileAsync(exeFile);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launching failed
}
}
Launcher.LaunchUriAsync
Reference: Can I use Windows.System.Launcher.LauncherDefaultProgram(Uri) to invoke another metro style app?

Looks like it’s not possible to open any non-metro processes. You can open URLs or Files like *.txt, but not *.cmd or *.exe.
If there is a Custom File Association you could possibly(I haven’t try this) start a process by opening an empty file with your custom filename extension. But you can’t edit the registry to add the association from your app.
So there are no App-Only ways to do this (except not yet discovered hacks ;) ).

Related

UWP: How do I read lyrics from a local music file?

The lyrics are nested in the music file, not downloaded from the internet. the MusicProperties does not have such attribute.
I have tried using Id3 package to read it and that requires path to the file. However, in UWP there seems no way to access a file using path like C:/Users/Seaky/Desktop/Music/SomeMusic.mp3 (at least not working for me as I get permission denied even with broadFileSystemAccess.).
What else can I try?
I have found a way to do that as Mp3 accepts a Stream object in its constructor. Therefore, I am able to do this:
public async Task<string> GetLyrics()
{
var file = await StorageFile.GetFileFromPathAsync(Path);
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
using (var mp3 = new Mp3(stream.AsStream()))
{
var lyrics = mp3.GetTag(Id3TagFamily.Version2X).Lyrics;
return lyrics.Count > 0 ? lyrics[0].Lyrics : "";
}
}
}
Accessing files from a UWP application outside a select number folders requires additional permissions.
As you've pointed out, you've added the broadFileSystemAccess capability to your app manifest, which should allow access to any file that the end-user has access to.
The broadFileSystemAccess capability still requires the end-user to authorize the application. The end-user is usually prompted to do this if broadFileSystemAccess capability is specified and the permission has not yet been granted, however, in some cases, this is broken. So you could check that the application has the required permissions, via the "Advanced Settings" link to your app under the Windows "Apps & settings" settings page.
If you're hardcoding the path, you could try letting the end-user pick the file using FileOpenPicker instead, to see if that makes a difference.
There is further information on file access permissions here.

Unauthorized access exception while running as admin

I know that there are a lot of questions concerning getting a
"System.UnauthorizedAccessException".
However I couldn't find a solution in any of these questions, as most of the answers refer to one of these Microsoft help pages.
My Situation:
I try to save some user input as .csv, so I can import it when needed.
My Code:
var csv = new System.Text.StringBuilder();
string dir = Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.DesktopDirectory), "test.csv");
var newLine = string.Format("{0},{1},{2},{3},{4}", txtFirstName.Text, txtLastName.Text, txtEmail.Text,
txtPhone.Text, txtPlace.Text);
csv.AppendLine(newLine);
if (!File.Exists(dir))
{
using (FileStream fs = File.Create(dir))
{
Byte[] info = new System.Text.UTF8Encoding(true).GetBytes("FirstName,LastName,Email,Phone,Place");
// Add headers to the file.
fs.Write(info, 0, info.Length);
}
}
try
{
File.AppendAllText(dir, csv.ToString());
}
catch (Exception ex)
{
throw ex;
}
As you can see, I'm trying to write everything to my Desktop, in a file called "test.csv". I am running Visual Studio as an Administrator and the file I have on my Desktop is not read-only.
Does anybodoy have an idea why this still fails?
Edit: I'm running this as a Standard UWP-App on a desktop Computer.
From a UWP process file access is restricted. In order to write to the desktop (or any arbitrary location) your app will need to use the file save dialog and let the user confirm/choose the location. Then you will be able to save to the desktop or whatever location the user has decided to select.
In the upcoming Spring 2018 update for Windows 10 we will introduce a new capability ('broadFileSystemAccess') for UWP applications that will make this better. If you declare this capability in your manifest, the app will ask for user consent on first launch for broad file system access, and then you will be able to access all locations that the current user has access to.
If you need a solution that works on earlier versions of Windows 10 (prior to Spring 2018 update) and the file dialog is not a viable option then you can look into adding a fulltrust process to your UWP package that handles the file operations on behalf of your UWP process. You can launch that fulltrust process from the UWP via the FullTrustProcessLauncher API: https://learn.microsoft.com/en-us/uwp/api/windows.applicationmodel.fulltrustprocesslauncher

How to autostart a c sharp application when booting windows?

I have a solution with two project files in it. One executable is a windows form application and the other one is a console application. Both executables perform different tasks, however, both need to be run at the same time (only the windows form has to be started). Therefore I added following code to my windows form application:
RegistryKey rkApp =
Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
true);
public Form1()
{
if (rkApp.GetValue("somename") == null)
{
rkApp.SetValue("somename", Application.ExecutablePath.ToString());
}
When I now restart the PC, everything's gone... Any ideas why this problem is turning up? Thank you!
P.S.: I'm a complete beginner, please be nice :)
You need to create a Windows Service Project and install with a service in windows.
If you have a .EXE file, you can add it to Start Up Programms using MSCONFIG from CMD, it's a Non-Coded Solution, but if you want it to attach to register as a service, then create a Windows Service Project.
Use REGEDIT to confirm that the 'somename' was added, also your code has the problem that it only checks 'somename' was previously set, not that the path is correct. If you ran the code in a different path during testing, it would never be updated. Also RegistryKey should be closed after you are finished with it. By rkApp.Close() or by 'using'.
using (RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
if (rkApp.GetValue("somename") != Application.ExecutablePath.ToString())
{
rkApp.SetValue("somename", Application.ExecutablePath.ToString());
}
}
You say only the form needs to be launched, does the form run the console? What happens?
Anothing possibility is when running a program by the registry, the 'Current Directory' is 'C:\Windows\System32' and not the application path. If you are using code such as:
File.ReadAllText('SomeFile.txt');
It would try opening C:\Windows\System32\SomeFile.txt and not \YourApp\SomeFile.txt, which can be fixed by:
// Reliably get the .EXE directory, this works for both Form and Console applications:
var AssemblyDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
// Option 1 is set on load:
Directory.SetCurrentDirectory(AssemblyDirectory);
// Option 2 is use full paths for anything opening files:
File.ReadAllText(AssemblyDirectory + "\\SomeFile.txt");

Running console application from a different project

I have a solution in VS2010. Under the solution, I have my main WPF application, with all the user interface, a couple of libraries, and a console application that I want to run when I click a button in my WPF application. My solution structure is similar to this:
- Solution
- WPF App [this is my startup project]
- Library
- Another library
- Console application
Now I have done some hunting around, and I've found people looking for how to reference code and classes, and also a solution to this being that I find the path of the executable, and run it as a new process. However, this requires knowing an absolute path, or even a relative path, and I was wondering if that's the only way I can start an application, even though it's in the same solution?
Yes,that is true. You must know the path to the executable, either absolute or relative. But that is no breakdown. Why don't you just put your WPF exe and Console exe in the same directory or in a subdirectory like in bin\myconsole.exe? When creating a new Process, just pass the name of the Console exe to Process.Start() and Windows will find your executable.
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace MyProcessSample
{
class MyProcess
{
// Opens the Internet Explorer application.
void OpenApplication(string myFavoritesPath)
{
// Start Internet Explorer. Defaults to the home page.
Process.Start("IExplore.exe");
// Display the contents of the favorites folder in the browser.
Process.Start(myFavoritesPath);
}
// Opens urls and .html documents using Internet Explorer.
void OpenWithArguments()
{
// url's are not considered documents. They can only be opened
// by passing them as arguments.
Process.Start("IExplore.exe", "www.northwindtraders.com");
// Start a Web page using a browser associated with .html and .asp files.
Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");
Process.Start("IExplore.exe", "C:\\myPath\\myFile.asp");
}
// Uses the ProcessStartInfo class to start new processes,
// both in a minimized mode.
void OpenWithStartInfo()
{
ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
Process.Start(startInfo);
startInfo.Arguments = "www.northwindtraders.com";
Process.Start(startInfo);
}
static void Main()
{
// Get the path that stores favorite links.
string myFavoritesPath =
Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
MyProcess myProcess = new MyProcess();
myProcess.OpenApplication(myFavoritesPath);
myProcess.OpenWithArguments();
myProcess.OpenWithStartInfo();
}
}
}
Look here.

Launching a Desktop Application with a Metro-style app

Is there a way to launch a desktop application from a Metro-style app on Windows 8? I'm trying to create some simple shortcuts to desktop applications to replace the desktop icons on the start screen, which look out of place.
I just need something super simple, preferably in C#, to open an application as soon as the app loads. I'm planning on making these shortcuts for some games, photoshop, etc, not anything I've made myself. They're also just for personal use, so I can use direct paths to applications like "C:\Program Files (x86)\Steam\steamapps\common\Skyrim\TESV.exe"
If you simply want to run a desktop application like (notepad, wordpad, internet explorer etc) then go through Process Methods and ProcessStartInfo Class
try
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "C:\Path\To\App.exe";
p.Start();
}
// Exp 2
// Uses the ProcessStartInfo class to start new processes,
// both in a minimized mode.
void OpenWithStartInfo()
{
ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
Process.Start(startInfo);
startInfo.Arguments = "www.northwindtraders.com";
Process.Start(startInfo);
}
On Windows 8 Metro application i discovered this: How to Start a
external Program from Metro App.
All the Metro-style applications work in the highly sand boxed
environment and there is no way to directly start an external
application.
You can try to use Launcher class – depends on your need it may
provide you a feasible solution.
Check this:
Can I use Windows.System.Launcher.LauncherDefaultProgram(Uri) to invoke another metro style app?
Ref: How to launch a Desktop app from within a Metro app?
Metro IE is a special app. You cannot invoke an executable from Metro style apps.
Try this - I have not test yet but may be it will help you..
Launcher.LaunchFileAsync
// Path to the file in the app package to launch
string exeFile = #"C:\Program Files (x86)\Steam\steamapps\common\Skyrim\TESV.exe";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(exeFile);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
I found a solution which is suitable for me. I just made an empty textfile in my app and called it launcher.yourappyouwanttostart and then executed it with
Windows.System.Launcher.LaunchFileAsync("launcher.yourappyouwanttostart");
On the first startup it asks you for the assocation for this file and then you choose the exe file you want to run and from now on every time you execute this file, your app will be started.
I haven't actually tried if it works and it's not really a beautiful solution, but I guess Metro-style apps can launch a URI.
You could then create a desktop-program that is registered for a custom URI scheme that would then do the actual program launching.
What you can do is host external WCF service on your computer with separate installation and connect to it from metro style application using localhost. Then you can do pretty much anything including Process.Start.
I love simple things, so my solution was to use this:
Process.Start("explorer", "shell:AppsFolder\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe!App")
This will start the "new" Sticky Notes coming with Anniversary Update to Windows 10, but it works with all other "Metro" apps I tested.
To find the name of the metro app, from Windows Explorer you have to find it in shell:appsfolder using the AppUserModelId column.

Categories