This snippet of code looks up the registered editor for the file type passed. If it doesn’t find one, it uses notepad (it was of course designed originally for text files).
Notice: See the cascading if statement both assigning and checking for null.
private void EditFile(string FilePath) { // Attempt to locate the system’s editor for this file type RegistryKey rkey = Registry.ClassesRoot.OpenSubKey(Path.GetExtension(FilePath)); if ((rkey != null) && ((rkey = Registry.ClassesRoot.OpenSubKey(rkey.GetValue(“”) + @”\shell\edit\command”)) != null) && (rkey.GetValue(“”).ToString() != String.Empty)) { ProcessStartInfo psi = new ProcessStartInfo();
// Don’t use the system’s shell psi.UseShellExecute = false;
// Replace the file parameter with this file psi.FileName = rkey.GetValue(“”).ToString().Replace(“%1”, FilePath);
// Begin execution Process.Start(psi); }
// The system editor could not be located, using Notepad else Process.Start(“notepad”, FilePath); }
|