Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to return an environment variable? [modified]

How to return an environment variable? [modified]

Scheduled Pinned Locked Moved C#
csharptutoriallinqgraphicsquestion
13 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T turbosupramk3

    I cannot get my environment variables to return a value in the message box in this example, but it works fine with things like "ipconfig" ... any idea as to why?

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;

    namespace WindowsFormsApplication4
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();

        }
    
        private void Form1\_Load(object sender, EventArgs e)
        {
            string testSession = ExecuteCommandSync("sessionname");
            MessageBox.Show(testSession);
        }
        public string ExecuteCommandSync(object command)
        {
            try
            {
                // create the ProcessStartInfo using "cmd" as the program to be run,
                // and "/c " as the parameters.
                // Incidentally, /c tells cmd that we want it to execute the command that follows,
                // and then exit.
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
                
                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = false;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                // Get the output into a string
                string result = proc.StandardOutput.ReadToEnd();
                //string result2 = System.Diagnostics.ProcessStartInfo( //procStartInfo("cmd", "/c " + command);
                return (result);
                // Display the command output.
                
            }
            catch (Exception objException)
            {
                // Log the exception
                return("failure");
            }
        }
    
    }
    

    }

    T Offline
    T Offline
    T M Gray
    wrote on last edited by
    #3

    Where in your code sample are you reading an environement variable? When asking why something is broken, show us the broken thing that is applicable, not some other thing that works fine. You do understand that each cmd process has its own environment right?

    T 1 Reply Last reply
    0
    • T turbosupramk3

      I cannot get my environment variables to return a value in the message box in this example, but it works fine with things like "ipconfig" ... any idea as to why?

      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Windows.Forms;
      using System.Net;
      using System.Net.Sockets;

      namespace WindowsFormsApplication4
      {
      public partial class Form1 : Form
      {
      public Form1()
      {
      InitializeComponent();

          }
      
          private void Form1\_Load(object sender, EventArgs e)
          {
              string testSession = ExecuteCommandSync("sessionname");
              MessageBox.Show(testSession);
          }
          public string ExecuteCommandSync(object command)
          {
              try
              {
                  // create the ProcessStartInfo using "cmd" as the program to be run,
                  // and "/c " as the parameters.
                  // Incidentally, /c tells cmd that we want it to execute the command that follows,
                  // and then exit.
                  System.Diagnostics.ProcessStartInfo procStartInfo =
                      new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
                  
                  // The following commands are needed to redirect the standard output.
                  // This means that it will be redirected to the Process.StandardOutput StreamReader.
                  procStartInfo.RedirectStandardOutput = true;
                  procStartInfo.UseShellExecute = false;
                  // Do not create the black window.
                  procStartInfo.CreateNoWindow = false;
                  // Now we create a process, assign its ProcessStartInfo and start it
                  System.Diagnostics.Process proc = new System.Diagnostics.Process();
                  proc.StartInfo = procStartInfo;
                  proc.Start();
                  // Get the output into a string
                  string result = proc.StandardOutput.ReadToEnd();
                  //string result2 = System.Diagnostics.ProcessStartInfo( //procStartInfo("cmd", "/c " + command);
                  return (result);
                  // Display the command output.
                  
              }
              catch (Exception objException)
              {
                  // Log the exception
                  return("failure");
              }
          }
      
      }
      

      }

      I Offline
      I Offline
      Ian Shlasko
      wrote on last edited by
      #4

      Like T M Gray said already... Where are you actually getting an environment variable in this code? And if that's your goal, why not just do it the easy way?

      string something = Environment.GetEnvironmentVariable("something");

      Not really sure what launching command-line processes and redirecting I/O has to do with environment variables...

      Proud to have finally moved to the A-Ark. Which one are you in?
      Author of the Guardians Saga (Sci-Fi/Fantasy novels)

      T 1 Reply Last reply
      0
      • T turbosupramk3

        I cannot get my environment variables to return a value in the message box in this example, but it works fine with things like "ipconfig" ... any idea as to why?

        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Linq;
        using System.Text;
        using System.Windows.Forms;
        using System.Net;
        using System.Net.Sockets;

        namespace WindowsFormsApplication4
        {
        public partial class Form1 : Form
        {
        public Form1()
        {
        InitializeComponent();

            }
        
            private void Form1\_Load(object sender, EventArgs e)
            {
                string testSession = ExecuteCommandSync("sessionname");
                MessageBox.Show(testSession);
            }
            public string ExecuteCommandSync(object command)
            {
                try
                {
                    // create the ProcessStartInfo using "cmd" as the program to be run,
                    // and "/c " as the parameters.
                    // Incidentally, /c tells cmd that we want it to execute the command that follows,
                    // and then exit.
                    System.Diagnostics.ProcessStartInfo procStartInfo =
                        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
                    
                    // The following commands are needed to redirect the standard output.
                    // This means that it will be redirected to the Process.StandardOutput StreamReader.
                    procStartInfo.RedirectStandardOutput = true;
                    procStartInfo.UseShellExecute = false;
                    // Do not create the black window.
                    procStartInfo.CreateNoWindow = false;
                    // Now we create a process, assign its ProcessStartInfo and start it
                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.StartInfo = procStartInfo;
                    proc.Start();
                    // Get the output into a string
                    string result = proc.StandardOutput.ReadToEnd();
                    //string result2 = System.Diagnostics.ProcessStartInfo( //procStartInfo("cmd", "/c " + command);
                    return (result);
                    // Display the command output.
                    
                }
                catch (Exception objException)
                {
                    // Log the exception
                    return("failure");
                }
            }
        
        }
        

        }

        P Offline
        P Offline
        PIEBALDconsult
        wrote on last edited by
        #5

        Because if you define a variable in another process, it won't exist in this one. :mad:

        T 1 Reply Last reply
        0
        • T T M Gray

          Where in your code sample are you reading an environement variable? When asking why something is broken, show us the broken thing that is applicable, not some other thing that works fine. You do understand that each cmd process has its own environment right?

          T Offline
          T Offline
          turbosupramk3
          wrote on last edited by
          #6

          I am asking for sessionname I had to replace ipconfig with sessionname in my original post, sorry about the confusion.

          1 Reply Last reply
          0
          • I Ian Shlasko

            Like T M Gray said already... Where are you actually getting an environment variable in this code? And if that's your goal, why not just do it the easy way?

            string something = Environment.GetEnvironmentVariable("something");

            Not really sure what launching command-line processes and redirecting I/O has to do with environment variables...

            Proud to have finally moved to the A-Ark. Which one are you in?
            Author of the Guardians Saga (Sci-Fi/Fantasy novels)

            T Offline
            T Offline
            turbosupramk3
            wrote on last edited by
            #7

            Hi, I tried that, and when I have a form that has a button/messagebox to check that and then display it, it keeps displaying the outdated variable value?

            1 Reply Last reply
            0
            • P PIEBALDconsult

              Because if you define a variable in another process, it won't exist in this one. :mad:

              T Offline
              T Offline
              turbosupramk3
              wrote on last edited by
              #8

              Hi, I'm not setting it, it will change by the OS ... but when I call it after the change it still does not display the new value?

              1 Reply Last reply
              0
              • T turbosupramk3

                I cannot get my environment variables to return a value in the message box in this example, but it works fine with things like "ipconfig" ... any idea as to why?

                using System;
                using System.Collections.Generic;
                using System.ComponentModel;
                using System.Data;
                using System.Drawing;
                using System.Linq;
                using System.Text;
                using System.Windows.Forms;
                using System.Net;
                using System.Net.Sockets;

                namespace WindowsFormsApplication4
                {
                public partial class Form1 : Form
                {
                public Form1()
                {
                InitializeComponent();

                    }
                
                    private void Form1\_Load(object sender, EventArgs e)
                    {
                        string testSession = ExecuteCommandSync("sessionname");
                        MessageBox.Show(testSession);
                    }
                    public string ExecuteCommandSync(object command)
                    {
                        try
                        {
                            // create the ProcessStartInfo using "cmd" as the program to be run,
                            // and "/c " as the parameters.
                            // Incidentally, /c tells cmd that we want it to execute the command that follows,
                            // and then exit.
                            System.Diagnostics.ProcessStartInfo procStartInfo =
                                new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
                            
                            // The following commands are needed to redirect the standard output.
                            // This means that it will be redirected to the Process.StandardOutput StreamReader.
                            procStartInfo.RedirectStandardOutput = true;
                            procStartInfo.UseShellExecute = false;
                            // Do not create the black window.
                            procStartInfo.CreateNoWindow = false;
                            // Now we create a process, assign its ProcessStartInfo and start it
                            System.Diagnostics.Process proc = new System.Diagnostics.Process();
                            proc.StartInfo = procStartInfo;
                            proc.Start();
                            // Get the output into a string
                            string result = proc.StandardOutput.ReadToEnd();
                            //string result2 = System.Diagnostics.ProcessStartInfo( //procStartInfo("cmd", "/c " + command);
                            return (result);
                            // Display the command output.
                            
                        }
                        catch (Exception objException)
                        {
                            // Log the exception
                            return("failure");
                        }
                    }
                
                }
                

                }

                D Offline
                D Offline
                Dr Walt Fair PE
                wrote on last edited by
                #9

                How are you checking the value? I'm not sure if this changed in the latest versions of Windows, but usually environment variables are initialized with a copy of the OS environment variables when the process starts. While the process is running, any changes in environment variables via the OS would not be seen by the process and any changes made to variables in the process will not be passed back to the OS.

                CQ de W5ALT

                Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                T 1 Reply Last reply
                0
                • D Dr Walt Fair PE

                  How are you checking the value? I'm not sure if this changed in the latest versions of Windows, but usually environment variables are initialized with a copy of the OS environment variables when the process starts. While the process is running, any changes in environment variables via the OS would not be seen by the process and any changes made to variables in the process will not be passed back to the OS.

                  CQ de W5ALT

                  Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                  T Offline
                  T Offline
                  turbosupramk3
                  wrote on last edited by
                  #10

                  Hi Walt, I've checked it both with the code above and by just calling the environment variable with a get environment variable call. Both times the code will not reflect the change until I restart the application I am building. I know the variable is changing though, because I can open a cmd prompt and type %sessionname% and it will reflect whether I am logged in locally or via console mode. I tried to keep spawning a new cmd prompt window within a form, so that it would close and then reopen the window and write the %sessionname% value, but closing the cmd window seems to kill my do while loop and I couldn't get around that even after 3 hours of trial and error :)

                  D 1 Reply Last reply
                  0
                  • T turbosupramk3

                    Hi Walt, I've checked it both with the code above and by just calling the environment variable with a get environment variable call. Both times the code will not reflect the change until I restart the application I am building. I know the variable is changing though, because I can open a cmd prompt and type %sessionname% and it will reflect whether I am logged in locally or via console mode. I tried to keep spawning a new cmd prompt window within a form, so that it would close and then reopen the window and write the %sessionname% value, but closing the cmd window seems to kill my do while loop and I couldn't get around that even after 3 hours of trial and error :)

                    D Offline
                    D Offline
                    Dr Walt Fair PE
                    wrote on last edited by
                    #11

                    Yes, that's what I would expect. The environment variables in your process and the OS and any other process are meant to be totally independent so that total chaos in the OS won't ensue. When you spawn your process (cmd window, etc.) it starts with a copy of the owner's environment variables, but any changes it makes are local to your process (cmd window) and any changes made in another process (a new cmd window or the OS) will not be seen by your process. I think you have confirmed that that's exactly what is happening. If you need to pass changeable information between processes, environment variables are not the solution. They are meant to be used for more or less static system information.

                    CQ de W5ALT

                    Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                    T 1 Reply Last reply
                    0
                    • D Dr Walt Fair PE

                      Yes, that's what I would expect. The environment variables in your process and the OS and any other process are meant to be totally independent so that total chaos in the OS won't ensue. When you spawn your process (cmd window, etc.) it starts with a copy of the owner's environment variables, but any changes it makes are local to your process (cmd window) and any changes made in another process (a new cmd window or the OS) will not be seen by your process. I think you have confirmed that that's exactly what is happening. If you need to pass changeable information between processes, environment variables are not the solution. They are meant to be used for more or less static system information.

                      CQ de W5ALT

                      Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                      T Offline
                      T Offline
                      turbosupramk3
                      wrote on last edited by
                      #12

                      Hi Walt, I thought it would load the environment variables in real time, not each time the program launches but that would explain my results. What would you suggest to monitor sessionname status? I'd ultimately like to create a service that runs under the local system account and monitors what type of connection someone is logged in under, be it console or RTP. Any suggestions?

                      D 1 Reply Last reply
                      0
                      • T turbosupramk3

                        Hi Walt, I thought it would load the environment variables in real time, not each time the program launches but that would explain my results. What would you suggest to monitor sessionname status? I'd ultimately like to create a service that runs under the local system account and monitors what type of connection someone is logged in under, be it console or RTP. Any suggestions?

                        D Offline
                        D Offline
                        Dr Walt Fair PE
                        wrote on last edited by
                        #13

                        Well, I'm no expert on the topic of inter-process communications! If everything is running on a single machine, I'd probably take the chicken way out and use a simple file to save information. But I suspect a true service would be much better and probably more scalable.

                        CQ de W5ALT

                        Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups