Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

.net - How do I launch files in C#

-Edit- I feel like an idiot. I had a feeling something like the answer below would work but didn't see any google results similar to the answers below. So when I saw this complex code I thought it had to be this way.

I searched and found this Windows: List and Launch applications associated with an extension however it didn't answer my question. With tweaks below, I came up with the below. However, it gets stuck on image files. Txt files run fine

I will update this code soon to account for app paths with spaces however I don't understand why image files don't launch.

static void launchFile(string fn)
{
    //majority was taken from
    //https://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension
    const string extPathTemplate = @"HKEY_CLASSES_ROOT{0}";
    const string cmdPathTemplate = @"HKEY_CLASSES_ROOT{0}shellopencommand";

    string ext = Path.GetExtension(fn);

    var extPath = string.Format(extPathTemplate, ext);

    var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string;
    if (!string.IsNullOrEmpty(docName))
    {
        // 2. Find out which command is associated with our extension
        var associatedCmdPath = string.Format(cmdPathTemplate, docName);
        var associatedCmd = Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string;

        if (!string.IsNullOrEmpty(associatedCmd))
        {
            //Console.WriteLine(""{0}" command is associated with {1} extension", associatedCmd, ext);
            var p = new Process();
            p.StartInfo.FileName = associatedCmd.Split(' ')[0];
            string s2 = associatedCmd.Substring(p.StartInfo.FileName.Length + 1);
            s2 = s2.Replace("%1", string.Format(""{0}"", fn));
            p.StartInfo.Arguments = s2;//string.Format(""{0}"", fn);
            p.Start();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use:

System.Diagnostics.Process.Start(filePath);

It will use the default program that would be opened as if you just clicked on it. Admittedly it doesn't let you choose the program that will run... but assuming that you want to mimic the behaviour that would be used if the user were to double-click on the file, this should work just fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...