ソフトの説明
FreamWork4.8から.net5に移行するとProcess.Startでつまづいたのでその回避方法です。
ブラウザでファイルを開かせたのですがJsonなどはIEが関連づけられており、その回避のため既定のブラウザをレジストリから取得しファイルを指定しブラウザで開きます。
プログラムの説明やフレームワーク4.8から.netアプリに対応させた個所
FW4.8では System.Diagnostics.Process.Start("https://www.yahoo.co.jp/")と書けば自動で関連ソフトを判断し起動してくれてましたが.net5からこれができなくなりました。
この回避策としては1つ目「UseShellExecute = true」をつかう。 2つ目は「Process.Start(New ProcessStartInfo("cmd", $"/c start {パス}") With {.CreateNoWindow = True})」とコマンドラインを噛ませる方法がありました。
しかし関連付けがおかしいと間違ったアプリで開いてしまいます。例Json⇒IE
そこで今回は既定のブラウザをレジストリから取得しさらにファイルを指定しブラウザで開きます。
form.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace process
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string progId = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice", false)
.GetValue("ProgId")
.ToString();
string command = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(
string.Format(@"{0}\shell\open\command", progId),
false)
.GetValue(null)
.ToString();
//"C:\Program Files\Mozilla Firefox\firefox.exe" -osint -url "%1"
//ファイパス以降になにやら文字が入るので削除 2つめの”を探してそれ以降を削除 Indexの使い方がちとおもろい
string gomi = command.Substring(command.IndexOf("\"", command.IndexOf("\"") + 1) + 1);
command = command.Replace(gomi, "");
string address = textBox1.Text;
var startInfo = new System.Diagnostics.ProcessStartInfo(address);
startInfo.UseShellExecute = true;
startInfo.FileName = command;
startInfo.Arguments = address;
Process.Start(startInfo);
//こうやって書いてもOK
//Process.Start(new ProcessStartInfo
//{
// UseShellExecute = true,
// FileName = command,
// Arguments = address,
//});
}
}
}