C#:输出当前用户/ IP /计算机名称等...到标签[重复]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#:输出当前用户/ IP /计算机名称等...到标签[重复]相关的知识,希望对你有一定的参考价值。

这个问题在这里已有答案:

我是相当新的c#并且每天学习更多虽然我坚持这个并且找不到类似的东西

在表单加载时,我想显示:*当前窗口用户*当前IP *主机名

和其他系统信息直接进入标签。任何指向我可以学习如何做这个或一个例子的指针

非常感激

答案

所有这些答案都来自现有的StackOverflow帖子。你真的应该努力一点。

当前用户:

  string userName = 
System.Security.Principal.WindowsIdentity.GetCurrent().Name;
 labelName.Text = userName;

目前的IP:

public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
    if (ip.AddressFamily == AddressFamily.InterNetwork)
    {
        return ip.ToString();
    }
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}

labelName.Text = GetLocalIPAddress();

主机名:

string hostName = System.Net.Dns.GetHostName();

labelName.Text = hostName;
另一答案

多年来我用这个课程来获取一些基本的机器信息。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;

namespace STUFF
{
    public static class WorkStation
    {
        public const ulong MEGABYTE = 1024 * 1024;
        public const ulong GIGABYTE = 1024 * 1024 * 1024;

        #region MEMORYSTATUSEX
        /// <summary>
        /// contains information about the current state of both physical and virtual memory, including extended memory
        /// </summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public class MEMORYSTATUSEX
        {
            /// <summary>
            /// Size of the structure, in bytes. You must set this member before calling GlobalMemoryStatusEx.
            /// </summary>
            public uint dwLength;

            /// <summary>
            /// Number between 0 and 100 that specifies the approximate percentage of physical memory that is in use (0 indicates no memory use and 100 indicates full memory use).
            /// </summary>
            public uint dwMemoryLoad;

            /// <summary>
            /// Total size of physical memory, in bytes.
            /// </summary>
            public ulong ullTotalPhys;

            /// <summary>
            /// Size of physical memory available, in bytes.
            /// </summary>
            public ulong ullAvailPhys;

            /// <summary>
            /// Size of the committed memory limit, in bytes. This is physical memory plus the size of the page file, minus a small overhead.
            /// </summary>
            public ulong ullTotalPageFile;

            /// <summary>
            /// Size of available memory to commit, in bytes. The limit is ullTotalPageFile.
            /// </summary>
            public ulong ullAvailPageFile;

            /// <summary>
            /// Total size of the user mode portion of the virtual address space of the calling process, in bytes.
            /// </summary>
            public ulong ullTotalVirtual;

            /// <summary>
            /// Size of unreserved and uncommitted memory in the user mode portion of the virtual address space of the calling process, in bytes.
            /// </summary>
            public ulong ullAvailVirtual;

            /// <summary>
            /// Size of unreserved and uncommitted memory in the extended portion of the virtual address space of the calling process, in bytes.
            /// </summary>
            public ulong ullAvailExtendedVirtual;

            /// <summary>
            /// Initializes a new instance of the <see cref="T:MEMORYSTATUSEX"/> class.
            /// </summary>
            public MEMORYSTATUSEX()
            {
                this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
            }
        }
        #endregion

        #region GlobalMemoryStatusEx
        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
        #endregion      

        #region GetSystemMetrics
        private const UInt16 SM_SERVERR2 = 89;

        [DllImport("user32.dll")]
        static extern int GetSystemMetrics([In] UInt16 smIndex);
        #endregion

        public static List<string> GetCPUInfo()
        {
            List<string> res = new List<string>();

            ManagementScope Scope = new ManagementScope(@"\" + Environment.MachineName + @"
ootcimv2");
            ObjectQuery Query = new ObjectQuery("SELECT Name FROM Win32_Processor");
            ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
            ManagementObjectCollection CollectionOfResults = Searcher.Get();

            res.Add(string.Format("{0} Processor(s)", Environment.ProcessorCount));
            foreach (ManagementObject CurrentObject in CollectionOfResults)
            {
                res.Add(CurrentObject["Name"].ToString());
            }

            return res;
        }

        public static List<string> GetDriveInfo()
        {
            List<string> res = new List<string>();

            DriveInfo[] dirs = DriveInfo.GetDrives();
            foreach (DriveInfo dir in dirs)
            {
                if ((dir.DriveType == DriveType.Fixed) && (dir.IsReady == true))
                {
                    res.Add(string.Format("Size of {0}: {1} GB", dir.Name, ((ulong)dir.TotalSize / GIGABYTE).ToString()));
                    res.Add(string.Format("Total Free Space: {0} GB", ((ulong)dir.TotalFreeSpace / GIGABYTE).ToString()));
                    res.Add(string.Format("Available Free Space: {0} GB", ((ulong)dir.AvailableFreeSpace / GIGABYTE).ToString()));
                }
            }

            return res;
        }

        public static List<string> GetGlobalizationInfo()
        {
            List<string> res = new List<string>();

            CultureInfo cultureInfo = CultureInfo.CurrentCulture;
            RegionInfo regionInfo = RegionInfo.CurrentRegion;
            TimeZoneInfo timeZoneInfo = TimeZoneInfo.Local;

            res.Add(string.Format("Culture: {0}", cultureInfo.EnglishName));
            res.Add(string.Format("Region: {0}", regionInfo.EnglishName));
            res.Add(string.Format("Time Zone: {0}", timeZoneInfo.Id));
            res.Add(string.Format("Daylight Savings Enabled: {0}", timeZoneInfo.SupportsDaylightSavingTime));
            res.Add(string.Format("In Daylight Savings: {0}", timeZoneInfo.IsDaylightSavingTime(DateTime.Now)));

            return res;
        }

        public static List<string> GetMemoryStatus()
        {
            List<string> res = new List<string>();

            MEMORYSTATUSEX msx = new MEMORYSTATUSEX();

            try
            {
                GlobalMemoryStatusEx(msx);

                double total = Math.Round((double)msx.ullTotalPhys / GIGABYTE, 2, MidpointRounding.AwayFromZero);
                double available = Math.Round((double)msx.ullAvailPhys / GIGABYTE, 2, MidpointRounding.AwayFromZero);
                double inUse = Math.Round((double)(msx.ullTotalPhys - msx.ullAvailPhys) / GIGABYTE, 2, MidpointRounding.AwayFromZero);

                res.Add(string.Format("Memory Load: {0}", msx.dwMemoryLoad));
                res.Add(string.Format("Total Physical (GB): {0}", total));
                res.Add(string.Format("In use (GB): {0}", inUse));
                res.Add(string.Format("Available (GB): {0}", available));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return res;
        }

        public static MachineInformation GetMachineInformation()
        {
            MachineInformation mi = new MachineInformation();

            try
            {
                ManagementClass osClass = ne

以上是关于C#:输出当前用户/ IP /计算机名称等...到标签[重复]的主要内容,如果未能解决你的问题,请参考以下文章

linux文件拷贝到其他机器

C# 获取本机mac地址 客户端主机名称(hostName) 当前用户(CurWinUser) 操作系统版本(WinVersion) IE浏览器版本(IEversion) 物理内存(Memo

Linux scp 命令使用方法

ubuntu scp

PowerShell批量部署Hyper-V Windows虚机

写一个C语言程序: 能修改Linux 主机的IP、DHCP、DNS 等设置