Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process.Start returns null

Tags:

c#

process

I'm writing a program that launches a random file in s directory. the file can be of any type, but mostly video or image files. Each time I launch a file I want to close the previous opened one.

Code :

string FolderSelected = "";
string FileName = "";
Process proc;
            
List<string> FilesDisplayed = new List<string>();

private void button2_Click(object sender, EventArgs e)
{
    if (FolderSelected == string.Empty)
        FolderSelected = Properties.Settings.Default.FilesDefaultFolder;

    if (proc != null)
    {
        proc.CloseMainWindow();
        proc.Close();
    }
    FileName = FetchRandomFile();
    proc = Process.Start(FileName);
}

Problem is, that I keep getting proc = null (the file is launched properly) and I cannot fetch the previously opened process in order to close it. I know that .NET reuses processes and that's why it returns Null but I need to override this behavior.

like image 289
gash25 Avatar asked Aug 11 '10 07:08

gash25


2 Answers

EDIT: Thanks to leppie's comment, I suspect I know the answer: my guess is that you're "starting" something like an image, and it's reusing an existing process to open the document instead of creating a new one.

I've reproduced this with this simple test app:

using System;
using System.Diagnostics;

public class Test
{
    static void Main()
    {
        Process proc = Process.Start("image.tif");
        Console.WriteLine(proc == null);
    }
}

This prints "true" because it's using dllhost.exe to host the Windows Image Viewer, rather than creating a new process.

like image 134
Jon Skeet Avatar answered Oct 27 '22 22:10

Jon Skeet


To fix this problem, you have to set UseShellExecute to false to bypass the shell.

Instead of

Process.Start("filename", "args")

use

Process.Start(new ProcessStartInfo() {
    FileName = "filename",
    Arguments = "args",
    UseShellExecute = false
});
like image 33
Despertar Avatar answered Oct 27 '22 23:10

Despertar