简体   繁体   中英

How can I pass a file path with %20 as an argument to a process?

I'm currently using C# to develop an app that will launch an app with given parameters (the app path and the document we're trying to open).

Here's the code I've tried so far:

var pi = new ProcessStartInfo(filePath)
{
        Arguments = "\"" + Path.GetFileName(filePath) + "\"",
        UseShellExecute = false,
        WorkingDirectory = Path.GetDirectoryName(filePath),
        FileName = appPath,
        Verb = "OPEN"
};
Process.Start(pi);

where filePath is the path to the file we want to open and appPath is the path of the app we want to open the file in ( C:\\Program Files\\...\\POWERPNT.exe ).

This solution works for files with and without spaces, however it doesn't work for files with '%20', which refuse to open in apps like PowerPoint. Example below:

"PowerPoint can't open this type of file (C:\\...\\...\\Statistics Made Easy.ppt)."

On Windows Explorer, the name of the file is Statistics%20Made%20Easy.ppt. Note that %20 got replaced by a space in the error message. What could the issue be?

One solution is to not set the working directory and use the full path for the file name instead:

var pi = new ProcessStartInfo(filePath)
{
        Arguments = "/ou \"" + filePath + "\"",                 // full path here
        UseShellExecute = false,
        // WorkingDirectory = Path.GetDirectoryName(filePath),  // skip this
        FileName = appPath,
        Verb = "OPEN"
};

If Powerpoint is the default app to open PPT files, you can also use

Process.Start(filePath);

without specifying pi at all. If the user changed the app to be used with PPT files, this might start a different app, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM