.netcore打开文件:根据文件类型,调用系统对应的工具打开文件。

 研究avalonia的时候,需要在mac 和linux上用系统工具打开对应的文件。于是写了此随笔。

 .netcore 根据文件类型,调用系统对应的工具打开文件。此功能可跨平台使用(在linux,windows,macos 上均可使用)

        /// <summary>
        /// 打开指定目录下的文件
        /// </summary>
        /// <param name="filePath">文件地址(包含文件名称)</param>
        /// <returns></returns>
        public static bool OpenFile(string filePath)
        {
            //filePath = Path.Combine(Path.GetDirectoryName(typeof(App).Assembly.Location), @"ppt3.png");
            //Console.WriteLine("filePath:" + 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;
        }

 

posted @ 2020-09-02 09:52  FrankFyy  阅读(757)  评论(0编辑  收藏  举报