C# - Easiest way to parse filename with spaces eg. "C:\Test\File with spaces.txt"

Dominic Bou-Samra picture Dominic Bou-Samra · Dec 7, 2009 · Viewed 29.3k times · Source

I am trying to pass a full file path to FFMPEG.

C:\TestFolder\Input\Friends - Season 6 - Gag Reel.avi

and it's obviously not liking the fact the path has spaces in it, erroring like so:

C:\TestFolder\Input\Friends: no such file or directory

So what's the easiest way to use filenames with spaces in them? Should I just replace all whitespaces with ~ characters or is there a better way? I have tried escaping the string with various characters:

@"C:\TestFolder\Input\Friends - Season 6 - Gag Reel.avi";

But this doesn't work. Is there a trick to preserving spaces?

Answer

Michael Petrotta picture Michael Petrotta · Dec 7, 2009

The only time you'll typically have to do any special handing with filenames that have spaces is when you're passing them to external tools or formats. If you're constructing an argument list for an external executable, for instance, all you have to do is quote the path:

string path = @"C:\TestFolder\Input\Friends - Season 6 - Gag Reel.avi";
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "program.exe";
psi.Arguments = "\"" + path + "\""; // escape the quotes

...which will result in this commandline:

program.exe "C:\TestFolder\Input\Friends - Season 6 - Gag Reel.avi"