Process.Start returns null

前端 未结 4 1330
情深已故
情深已故 2020-12-16 12:05

i am writing a program that launches a random file in a directory. the file can be of any time, but mostly video or image files. each time i launch a file i want to close th

相关标签:
4条回答
  • 2020-12-16 12:11

    You are declaring 'proc' at method scope, so of course it will always be null when checked at the top of that method. If you want the reference to live beyond the function, declare it is a class level variable.

    You are spawning a process each time (probably), Process.Start is not returning null, but you simply lose the reference to it when i goes out of scope.

    0 讨论(0)
  • 2020-12-16 12:18

    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
    }
    
    0 讨论(0)
  • 2020-12-16 12:18

    That won't even compile (definite assignment). As a method variable, proc is local only to the declaring method(/scope) - i.e. button2_Click, which explains why you can't retain values. If proc is meant to persist between calls, promote it to a field (per-instance variable):

    Process proc;
    private void button2_Click(object sender, EventArgs e)
    {
        if (proc != null)
        ...
    
    0 讨论(0)
  • 2020-12-16 12:29

    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.

    0 讨论(0)
提交回复
热议问题