Solved

How can I get remote Machine Name where Console Application resides when it executes?

Posted on 2012-03-26
11
531 Views
Last Modified: 2012-04-02
I am working on an intranet and have 3 different machines: Development, Test, Production. My Development machine is my laptop; the Test machine is a remote server; the Production machine is a different remote server. I built a simple Console Application using C#, and I would like for it to show me the Machine's name (or domain name) where the executable is actually residing when it is run. It may be running from my laptop machine, but I want it to show me the name of the machine where it resides.

Currently I have tried both of the following, but they both give me my laptop's machine name:

using System.Net;             //For Dns

            string machineName = Environment.MachineName.ToString();
            string strHostName = Dns.GetHostName();

What can I do or use to get the machine name (or host name) of the machine where the Console Application resides when it executes?
0
Comment
Question by:dwoolley3
  • 4
  • 4
  • 3
11 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
Comment Utility
This gives you dev machine name when you run it on server? Strange. Are the names of two machines different? You are not storing the name anywhere are you?
0
 

Author Comment

by:dwoolley3
Comment Utility
Both commands give me the Dev machine name when I use my laptop to navigate to the Test server (via Windows Mappings) and execute the Console Application executable that resides on the Test server.  From one perspective, I suppose it is executing on my laptop. Is there a way to have it show that the executable actually resides on the Test machine?
0
 
LVL 27

Assisted Solution

by:Ark
Ark earned 250 total points
Comment Utility
When you run executable from remote machine, actually it copies into your machine memory and execute there. You can use Application.StartupPath to get a folder where *.exe file located and then parse it. For local machine you'll get ":" (drive name separator) as a second char
If Application.StartupPath.Substring(1,1)=":" then
   mName=Environment.MachineName
Else
'Here you'll get share name
End If
0
 

Author Comment

by:dwoolley3
Comment Utility
Nice thought Ark, yet it seems that Application.StartUp is only available for Windows Applications (as opposed to Console Applications). I tried to add the namespace System.Windows.Forms, but VS 2008 says that the namespace Windows does not exist in the namespace System.

Perhaps the answer to my question is that I can't get the info that I want when I run the executable remotely from my laptop, since it seems to copy the executable into machine memory and executes it from there (as mentioned by Ark).
0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 250 total points
Comment Utility
I assumed that you are running the exe on the server when you said it resides on the server.

Try

System.AppDomain.CurrentDomain.BaseDirectory

to get the startup path.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:dwoolley3
Comment Utility
Thanks, though the System.AppDomain.CurrentDomain.BaseDirectory is not what I need.

I am able to accomplish my goal of determining whether the machine is production or not by using either

string machineName = Environment.MachineName.ToString();
string strHostName = Dns.GetHostName();

The only catch is that it will show the machine Name that is running the executable and not the machine that is storing the executable. In my case, I can live with this because the production run will be scheduled through SQL Server's Job scheduler that runs on the same production machine. Thus, in production mode, the job will run on the production machine and the program will detect the correct machineName.
0
 
LVL 83

Expert Comment

by:CodeCruiser
Comment Utility
That was a known part I thought.
0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
I tried to add the namespace System.Windows.Forms
Winform app add reference to windows.forms automatically. To use this namespace in console app, add reference either from .Net components or directly to system.windows.forms.dll
0
 

Author Comment

by:dwoolley3
Comment Utility
Thank you both for your suggestions, both of which I tested. I added the reference to system.windows.forms.dll -- thank you for that technique.

            string startupPath = Application.StartupPath;
            string baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            Console.WriteLine("StarupPath = " + startupPath);
            Console.WriteLine("BaseDirectory = " + baseDirectory);

With the above code, my executable will produce a complete path only on Development machine:
on Dev machine: C:\Inetpub\wwwroot\etc.
on Test machine: O:\
on Prod machine: A:\

The Test and Prod machine return 3 characters indicating the drive that I have assigned the mapping to from my local machine. If my partner runs these executables from his machine, the drives will be different based on which drives he mapped to the test machine and production machine. We are not logging onto these machines remotely but we are mapping to them through Windows Explorer. Although I would like to have the program differentiate these three environments and thus access things specific to those three environments (like a different database), I am willing to settle for the program differentiating between this kind of a run and the real production run that gets executed on the production machine via SQL Server Job Scheduler.
0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
  <DllImport("mpr.dll")> _
    Shared Function WNetGetConnection(<MarshalAs(UnmanagedType.LPTStr)> _
                      ByVal localName As String, ByVal remoteName As System.Text.StringBuilder, _
                      ByRef length As Integer) As Integer
    End Function
    Private Function pathToUnc(ByVal path As String)
        Dim length As Integer = 255
        Dim UNC As New System.Text.StringBuilder(length)
        WNetGetConnection(path.Substring(0, 2), UNC, length)
        Return UNC.ToString
    End Function
    
    Private Sub Test()
        Dim dr As String = "O:\"
        MsgBox("The UNC-Path of drive " & dr & " is: " & strToUnc(dr))
    End Sub

Open in new window

0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
Oops, sorry, seems u'r using CSharp:
DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int WNetGetConnection(
            [MarshalAs(UnmanagedType.LPTStr)] string localName,
            [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
            ref int length);

        public static string GetUNCPath(string originalPath)
        {
            StringBuilder sb = new StringBuilder(512);
            int size = sb.Capacity;
            // look for the {LETTER}: combination ...
            if (originalPath.Length > 2 && originalPath[1] == ':')
            {
                // don't use char.IsLetter here - as that can be misleading
                // the only valid drive letters are a-z && A-Z.
                char c = originalPath[0];
                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
                {
                    int error = WNetGetConnection(originalPath.Substring(0, 2),
                        sb, ref size);
                    if (error == 0)
                    {
                        DirectoryInfo dir = new DirectoryInfo(originalPath);
                        string path = Path.GetFullPath(originalPath)
                            .Substring(Path.GetPathRoot(originalPath).Length);
                        return Path.Combine(sb.ToString().TrimEnd(), path);
                    }
                }
            }

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now