.NetCore调用Shell模式打开外部资源

1.简介

在做跨平台项目时,我们总是需要通过程序打开外部的文件或者网址等。本文就是介绍的这个方法。

2.操作

解决思路,是根据系统环境不同,分别调用系统的Shell模式去调用外部程序。
代码如下:

        /// <summary>
        /// 文件或者地址
        /// </summary>
        /// <param name="filePath">文件地址(包含文件名称)</param>
        /// <returns></returns>
        public static bool OpenFile(string filePath)
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))                       //windows环境下打开文件
                {
                    filePath = filePath.Replace("&", "^&");
                    Process.Start(new ProcessStartInfo("cmd", $"/c start {filePath}") { CreateNoWindow = true });
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))                     //Linux环境下打开文件
                {
                    Process.Start("xdg-open", filePath);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))                       //Mac环境下打开文件
                {
                    Process.Start("open", filePath);
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

3.总结

只是一个小技巧,积累即可。方便自己,方便大家。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laiger90

众筹一元加个菜~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值