Search code examples
c#registryquotesdirectoryinfo

Other way to put a path in quotes when using DirectoryInfo?


I'm currently working with reg.exe and I'm creating a process with reg.exe as the Process.FileName.

When I try to execute reg.exe like following

REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS D:\\Backups\\Test.reg

everthing works fine.

But as soon as I try to execute it like this

REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS D:\\Backups\\Backup folder 1\\Test.reg 

nothing happens - and I know why! The target path isn't put in quotes. As soon as I do that everything works fine again.

My problem now is that I'm handling all my file and folder paths as instances of DirectoryInfo. When I pass the path with quotes as a string, e.g. like that

DirectoryInfo targetFolder = new DirectoryInfo("\"D:\\Backups\\Backup folder 1\\Test.reg\"")

I instantly receive an exception telling me that the given path's format is not supported.

Is there any way to put the path in quotes and still work with DirecotryInfo? I really need to put my path in quotes - otherwise the command won't work.

Here's some example code:

DirectoryInfo backupPath = new DirectoryInfo("D:\\Backups\\Backup folder 1\\Test.reg");

Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();

startInfo.FileName = "reg.exe";
startInfo.CreateNoWindow = true;
startInfo.Arguments = "REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS " + backupPath.FullName;

process.StartInfo = startInfo;
process.Start();
process.WaitForExit();

When I run this code, nothing happens - nor errors or exceptions. The .reg file itself isn't created either.

When I try to run it like this

DirectoryInfo backupPath = new DirectoryInfo("\"D:\\Backups\\Backup folder 1\\Test.reg\"");

Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();

startInfo.FileName = "reg.exe";
startInfo.CreateNoWindow = true;
startInfo.Arguments = "REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS " + backupPath.FullName;

process.StartInfo = startInfo;
process.Start();
process.WaitForExit();

I'm getting a System.NotSupportedException telling me "The given path's format is not supported." But I actually need to put the path in quotes - otherwise the command itself won't work...


Solution

  • You are adding quotes in the wrong place: constructor of DirectoryInfo will strip them anyway to normalize the path, so you can skip adding them:

    var backupPath = new DirectoryInfo("D:\\Backups\\Backup folder 1\\Test.reg");
    

    You can force quotes around the path when you add backupPath.FullName to the arguments, like this:

    startInfo.Arguments = "REG EXPORT HKLM\SOFTWARE\Intel\IntelAMTUNS \"" + backupPath.FullName + "\"";