首页 > 解决方案 > 如何使用 .NET Core 2.1 中的 Process.Start 使用默认程序打开网络共享驱动器上的文件

问题描述

我有点困惑。我已经构建了一个 Intranet 应用程序,该应用程序具有允许用户将文件“上传”到网络共享驱动器的功能。这不是问题,因为我能够成功地将文件复制到指定文件夹。复制文件后,下一个要求是让用户单击附件的链接并使用默认程序打开文件(即 Notepad.exe 用于 .txt 扩展名等)。使用 Process.Start 我已经在我的 localhost 机器上成功演示了这一点,但是,当应用程序发布到主机服务器时会出现问题,因为它最初给出了“访问被拒绝”错误。设置网络文件夹后' s 接受服务帐户的权限并将应用程序池标识更改为该服务帐户,它不再引发权限错误。事实上,它根本不会引发错误。就像在本地主机上一样,它一直通过函数,但它显然没有打开文件,而不是什么都不做。至少在我看来,好像应用程序“认为”它已经打开了程序,因此继续前进,好像没有任何问题。我在这里真的很茫然。我显然错过了一些东西,但我一生都无法弄清楚。

这是打开文件的函数:

ActivityLog activityLog = new ActivityLog();
FileInfo fileInfo = new FileInfo(filePath);
Process process = new Process();
try
{
    if (fileInfo.Exists)
    {
        //I've used both UseShellExecute and the
        //command line arguments with the same results.

        /*
        process.StartInfo = new ProcessStartInfo
        {
            FileName = fileInfo.FullName,
            WorkingDirectory = fileInfo.DirectoryName,
            UseShellExecute = true
        };
        */

        process.StartInfo = new ProcessStartInfo("cmd", $"/c start " + fileInfo.FullName.FileStringToUri());
        process.Start();
    }
    else throw new Exception("FileInfo not found | File Path: " + filePath);
}
catch (Exception e)
{
    if (fileInfo.Exists)
        activityLog.LogErrorAsync(new Exception("File Path: " + fileInfo.FullName + " | " + e.Message, e));
    else
        activityLog.LogErrorAsync(e);
    throw e;
}

FileStringToUri()是一个自定义扩展,它本质上创建了一个类似于 的 uri 字符串,但如果使用该方法file://{file}/{path},则不需要此扩展。UseShellExecute

标签: c#.net.net-coreprocess.start.net-core-2.1

解决方案


收盘票。按原样回答,在评论中。谢谢@damien-the-unbeliever


推荐阅读