Is it possible to copy something to the clipboard using .Net Core (in a platform-agnostic way)?
It seems that the Clipboard class is missing, and P/Invoking is
Clipboard class is missing, hope in near future will be add an option for that. While it happen ... you can run a native shell command with ProcessStartInfo.
I'm noob in Net Core, but create this code to send and string to clipboard on Windows and Mac:
OS Detection Class
public static class OperatingSystem
{
public static bool IsWindows() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
public static bool IsMacOS() =>
RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
public static bool IsLinux() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
}
Shell Class
Based on https://loune.net/2017/06/running-shell-bash-commands-in-net-core/
public static class Shell
{
public static string Bash(this string cmd)
{
var escapedArgs = cmd.Replace("\"", "\\\"");
string result = Run("/bin/bash", $"-c \"{escapedArgs}\"");
return result;
}
public static string Bat(this string cmd)
{
var escapedArgs = cmd.Replace("\"", "\\\"");
string result = Run("cmd.exe", $"/c \"{escapedArgs}\"");
return result;
}
private static string Run (string filename, string arguments){
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = filename,
Arguments = arguments,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = false,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
}
Clipboard Class
public static class Clipboard
{
public static void Copy(string val)
{
if (OperatingSystem.IsWindows())
{
$"echo {val} | clip".Bat();
}
if (OperatingSystem.IsMacOS())
{
$"echo \"{val}\" | pbcopy".Bash();
}
}
}
Then Finally, you can call Clipboard Copy and can get the value on the clipboard.
var dirPath = @"C:\MyPath";
Clipboard.Copy(dirPath);
Hope it help others! Improvements are welcome.
I'm working in a ToolBox library for .net core with all this things: https://github.com/deinsoftware/toolbox (also available as NuGet Package).
Run a command in external terminal with .Net Core: https://dev.to/deinsoftware/run-a-command-in-external-terminal-with-net-core-d4l