Search code examples
c#.net.net-coreprocess.start.net-core-2.1

How to open a file on a network share drive with the default program using Process.Start in .NET Core 2.1


I have a bit of a perplexing quandary. I've built an intranet application with a feature that allows a user to "upload" a file to a network share drive. This isn't the problem though as I am able to successfully copy a file to the designated folder. Having copied the file over the next requirement is to let the user click on a link for the attachment and open the file with the default programs (ie. Notepad.exe for .txt extensions and so on). Using Process.Start I have successfully demonstrated this on my localhost machine, however, the problem occurs when the application is published to the host server as it had originally given the "Access is denied" error. After setting the network folder's permissions to accept a service account and changing the Application Pool Identity to that service account it no longer throws a permission error. In fact it doesn't throw an error at all. It makes it all the way through the function as it would on the localhost, but instead of opening the file it apparently does nothing. It appears, at least to me, as though the application "thinks" it has opened the program and therefore moves on as if nothing's wrong. I'm really at a loss here. I'm clearly missing something, but I can't for the life of me figure it out.

This is the function to open the file:

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() is a custom extension that essentially creates a uri string similar to file://{file}/{path}, but this extension is not necessary if using the UseShellExecute method.


Solution

  • Closing ticket. Answer, as it is, in the comments. Thank you @damien-the-unbeliever