Skip to content

Instantly share code, notes, and snippets.

@parsiya
Last active March 22, 2021 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parsiya/f235882ed04c4f881064a12dc7b6be15 to your computer and use it in GitHub Desktop.
Save parsiya/f235882ed04c4f881064a12dc7b6be15 to your computer and use it in GitHub Desktop.
Pass the input as the first argument. You can pass schemes (`ms-calculator://whatever`) or files (`C:/windows/system32/calc.exe).
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace runme
{
class Program
{
static void Main(string[] args)
{
string nem = args[0];
OpenFileOrUrl(new Uri(nem).ToString());
}
public static void OpenFileOrUrl(string pathOrUri)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
// Is the scheme not http or https?
if (!IsPathForBrowser(pathOrUri))
{
Console.WriteLine(String.Format("Executing: Process.Start({0});", pathOrUri));
Process.Start(pathOrUri);
return;
}
}
catch (Exception exception)
{
Console.WriteLine("Error in Process.Start");
Console.WriteLine(exception.ToString());
}
pathOrUri = "\"" + pathOrUri + "\"";
Console.WriteLine(String.Format("Executing: explorer.exe {0}", pathOrUri));
Process.Start("explorer.exe", pathOrUri);
return;
}
Process.Start("open", pathOrUri);
}
private static bool IsPathForBrowser(string path)
{
return Uri.IsWellFormedUriString(path, UriKind.Absolute) && IsUriForBrowser(new Uri(path));
}
private static bool IsUriForBrowser(Uri uri)
{
return (uri.Scheme == Uri.UriSchemeHttp) || (uri.Scheme == Uri.UriSchemeHttps);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment