modify the path environment variable

G

Guest

I have a need within an application to modify the path environment variable,
as I need to find specific directories and remove them. I use the following
code to do this:

RegistryKey rkey = null;
rkey =
Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session
Manager\Environment",true);
string p = (String)rkey.GetValue("Path");
string[] pp = p.Split(';');
string outPath = "";
foreach(string t in pp) {
string t2 = t.ToUpper();
if (t2.IndexOf("MQCLIENT") < 0) {
outPath += t + ";";
}
}
rkey.SetValue("Path",p);
rkey.Close();

I break the path apart into an array using the semi-colon delimiter. If the
string I'm looking for isn't in this folder, it gets added to the out path
string. This works about 95% of the time. Sometimes it just seems like the
app isn't able to modify this value. It doesn't generate any exceptions, it
just doesn't change the path as it should. It happens on XP machines as well
as Win2k machines. The folder I want to remove has been in varying spots in
the path. I haven't been able to discover anything consistent about the
machines where this fails. I checked permissions on this registry section,
even changing it so Everyone had full access, and it made no difference.
There has to be something in my code that I'm missing, but what that is, I
don't know.
 
G

Guest

I assume this is not the actual code because it should not work at all. You
are assigning the registry value of the Path to the variable "p" and then
updating the registry with the same value.

string p = (String)rkey.GetValue("Path");
..
..
..
rkey.SetValue("Path",p);

There is also a problem with your foreach loop. If the value is not in the
path, you will end up adding it over and over again. You don't need to loop
at all, just look at the entire path and determine if the specific value is
anywhere in it and add it if necessary.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top