如何在.NET Core 2.1中使用Process.Start使用默认程序在网络共享驱动器上打开文件

时间:2019-02-15 04:09:39

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

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

这是打开文件的功能:

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()是一个自定义扩展名,本质上创建了一个类似于file://{file}/{path}的uri字符串,但是如果使用UseShellExecute方法,则不需要此扩展名。

1 个答案:

答案 0 :(得分:0)

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