C#프로그래머가 자주 사용하는 유틸리티 코드 세션 10개
18398 단어 C#
1 운영 체제 및 CLR 버전 읽기
OperatingSystem os = System.Environment.OSVersion;
Console.WriteLine(“Platform: {0}”, os.Platform);
Console.WriteLine(“Service Pack: {0}”, os.ServicePack);
Console.WriteLine(“Version: {0}”, os.Version);
Console.WriteLine(“VersionString: {0}”, os.VersionString);
Console.WriteLine(“CLR Version: {0}”, System.Environment.Version);
Windows 7 시스템에서 다음 정보를 출력합니다.
Platform: Win32NT
Service Pack:
Version: 6.1.7600.0
VersionString: Microsoft Windows NT 6.1.7600.0
CLR Version: 4.0.21006.1
2 읽기 CPU 수, 메모리 용량
Windows Management Instrumentation(WMI)에서 제공하는 인터페이스를 통해 필요한 정보를 읽을 수 있습니다.
private static UInt32 CountPhysicalProcessors()
{
ManagementObjectSearcher objects = new ManagementObjectSearcher(
“SELECT * FROM Win32_ComputerSystem”);
ManagementObjectCollection coll = objects.Get();
foreach(ManagementObject obj in coll)
{
return (UInt32)obj[“NumberOfProcessors”];
}
return 0;
}
private static UInt64 CountPhysicalMemory()
{
ManagementObjectSearcher objects =new ManagementObjectSearcher(
“SELECT * FROM Win32_PhysicalMemory”);
ManagementObjectCollection coll = objects.Get();
UInt64 total = 0;
foreach (ManagementObject obj in coll)
{
total += (UInt64)obj[“Capacity”];
}
return total;
}
프로그램 집합 시스템을 추가하십시오.Management의 참조로 코드가 제대로 컴파일되었는지 확인합니다.
Console.WriteLine(“Machine: {0}”, Environment.MachineName);
Console.WriteLine(“# of processors (logical): {0}”, Environment.ProcessorCount);
Console.WriteLine(“# of processors (physical): {0}” CountPhysicalProcessors());
Console.WriteLine(“RAM installed: {0:N0} bytes”, CountPhysicalMemory());
Console.WriteLine(“Is OS 64-bit? {0}”, Environment.Is64BitOperatingSystem);
Console.WriteLine(“Is process 64-bit? {0}”, Environment.Is64BitProcess);
Console.WriteLine(“Little-endian: {0}”, BitConverter.IsLittleEndian);
foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
{
Console.WriteLine(“Screen {0}”, screen.DeviceName);
Console.WriteLine(“\tPrimary {0}”, screen.Primary);
Console.WriteLine(“\tBounds: {0}”, screen.Bounds);
Console.WriteLine(“\tWorking Area: {0}”,screen.WorkingArea);
Console.WriteLine(“\tBitsPerPixel: {0}”,screen.BitsPerPixel);
}
3 레지스트리 키 값 쌍 읽기
using (RegistryKey keyRun = Registry.LocalMachine.OpenSubKey(@”Software\Microsoft\Windows\CurrentVersion\Run”))
{
foreach (string valueName in keyRun.GetValueNames())
{
Console.WriteLine(“Name: {0}\tValue: {1}”, valueName, keyRun.GetValue(valueName));
}
}
네임스페이스 Microsoft를 추가하십시오.Win32 위 코드를 컴파일할 수 있는지 확인합니다.
4 Windows 서비스 시작, 중지
이 API가 제공하는 실용 기능은 종종 프로그램의 서비스를 관리하는 데 사용되며, 제어판의 관리 서비스에 가서 조작할 필요가 없다.
ServiceController controller = new ServiceController(“e-M-POWER”);
controller.Start();
if (controller.CanPauseAndContinue)
{
controller.Pause();
controller.Continue();
}
controller.Stop();
.net에서 제공하는 API에서 한마디 설치 및 마운트 해제 서비스를 실현할 수 있습니다
if (args[0] == "/i")
{
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
}
else if (args[0] == "/u")
{
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
}
코드와 같이 프로그램에 i 또는 u 파라미터를 보내서 마운트 해제나 설치 프로그램을 표시합니다.
5 프로그램에 strong name(P/Invoke)이 있는지 확인합니다.
예를 들어 프로그램에서 프로그램 집합에 서명이 있는지 확인하기 위해 다음과 같은 방법을 호출할 수 있습니다.
[DllImport("mscoree.dll", CharSet=CharSet.Unicode)]
static extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool pfWasVerified);
bool notForced = false;
bool verified = StrongNameSignatureVerificationEx(assembly, false, ref notForced);
Console.WriteLine("Verified: {0}
Forced: {1}", verified, !notForced);
이 기능은 서명된 구성 요소를 검증하는 데 자주 사용되는 소프트웨어 보호 방법입니다.서명이 지워지거나 모든 프로그램 집합의 서명이 지워져도 프로그램에 호출 코드가 있으면 프로그램 실행을 멈출 수 있습니다.
6 시스템 구성 변경 사항에 대응
예를 들어 우리가 시스템을 잠근 후에 QQ가 종료되지 않으면 바쁜 상태를 보일 것이다.
네임스페이스 Microsoft를 추가하십시오.Win32 다음 이벤트를 등록하십시오.
. DisplaySettingsChanged(Changing 포함) 디스플레이 설정
. InstalledFontsChanged 글꼴 변경 내용
. PaletteChanged
. PowerModeChanged 전원 상태
. SessionEnded(사용자가 로그아웃 중이거나 세션이 종료됨)
. SessionSwitch(현재 사용자 변경)
. TimeChanged 시간 변경
. UserPreferenceChanged(사용자 편향에 Changing 포함)
우리의 ERP 시스템은 시스템의 시간이 바뀌었는지 모니터링할 것입니다. 만약 시간을 조정한 후 ERP 허가 파일 이외의 범위를 사용하면 ERP 소프트웨어를 사용할 수 없습니다.
7 Windows 7의 새로운 기능 활용
윈도 7 시스템은 파일 대화상자를 열면 현재 작업의 진도를 표시합니다.
Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog ofd =new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();
ofd.AddToMostRecentlyUsedList = true;
ofd.IsFolderPicker = true;
ofd.AllowNonFileSystemItems = true;
ofd.ShowDialog();
이러한 방법으로 대화상자를 열면 BCL 자체 라이브러리의 OpenFileDialog 기능과 더 많은 기능을 사용할 수 있습니다.Windows 7 시스템에만 해당되므로 이 코드를 호출하려면 운영 체제의 버전이 6 이상이어야 하며 Microsoft 용 프로그램 세트 Windows API Code Pack 을 추가해야 합니다.®.NET Framework의 참조는 이 주소에서 다운로드하십시오.http://code.msdn.microsoft.com/WindowsAPICodePack
8 메모리 소모량 검사
아래의 방법으로 검사할 수 있다.NET가 프로그램에 할당한 메모리 수:
long available = GC.GetTotalMemory(false);
Console.WriteLine(“Before allocations: {0:N0}”, available);
int allocSize = 40000000;
byte[] bigArray = new byte[allocSize];
available = GC.GetTotalMemory(false);
Console.WriteLine(“After allocations: {0:N0}”, available);
내 시스템에서 실행된 결과는 다음과 같습니다.
Before allocations: 651,064
After allocations: 40,690,080
다음 방법을 사용하여 현재 애플리케이션에서 사용 중인 메모리를 확인할 수 있습니다.
Process proc = Process.GetCurrentProcess();
Console.WriteLine(“Process Info: “+Environment.NewLine+
“Private Memory Size: {0:N0}”+Environment.NewLine +
“Virtual Memory Size: {1:N0}” + Environment.NewLine +
“Working Set Size: {2:N0}” + Environment.NewLine +
“Paged Memory Size: {3:N0}” + Environment.NewLine +
“Paged System Memory Size: {4:N0}” + Environment.NewLine +
“Non-paged System Memory Size: {5:N0}” + Environment.NewLine,
proc.PrivateMemorySize64, proc.VirtualMemorySize64, proc.WorkingSet64, proc.PagedMemorySize64, proc.PagedSystemMemorySize64, proc.NonpagedSystemMemorySize64 );
9 초시계 검사 프로그램 실행 시간 사용하기
만약 어떤 코드가 시간이 많이 걸릴까 봐 걱정된다면, 다음 코드와 같이 StopWatch로 이 코드가 소모된 시간을 검사할 수 있습니다.
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
Decimal total = 0;
int limit = 1000000;
for (int i = 0; i < limit; ++i)
{
total = total + (Decimal)Math.Sqrt(i);
}
timer.Stop();
Console.WriteLine(“Sum of sqrts: {0}”,total);
Console.WriteLine(“Elapsed milliseconds: {0}”,
timer.ElapsedMilliseconds);
Console.WriteLine(“Elapsed time: {0}”, timer.Elapsed);
현재 프로그램의 운행 시간을 측정하는 전문적인 도구가 있는데, 예를 들어dotNetPerformance 소프트웨어와 같은 모든 방법을 세분화할 수 있다.
위의 코드를 예로 들면 원본 코드를 직접 수정해야 합니다. 테스트 프로그램이라면 불편합니다.아래의 예를 참고하시오.
class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable
{
public AutoStopwatch()
{
Start();
}
public void Dispose()
{
Stop();
Console.WriteLine(“Elapsed: {0}”, this.Elapsed);
}
}
using 문법을 빌려 아래 코드와 같이 코드의 운행 시간을 확인하고 컨트롤러에 출력할 수 있습니다.
using (new AutoStopwatch())
{
Decimal total2 = 0;
int limit2 = 1000000;
for (int i = 0; i < limit2; ++i)
{
total2 = total2 + (Decimal)Math.Sqrt(i);
}
}
10 커서 사용
프로그램이 백그라운드에서 저장이나 해제 작업을 실행하고 있을 때 커서 상태를 바쁘게 수정해야 합니다.아래의 기교를 사용할 수 있다.
class AutoWaitCursor : IDisposable
{
private Control _target;
private Cursor _prevCursor = Cursors.Default;
public AutoWaitCursor(Control control)
{
if (control == null)
{
throw new ArgumentNullException(“control”);
}
_target = control;
_prevCursor = _target.Cursor;
_target.Cursor = Cursors.WaitCursor;
}
public void Dispose()
{
_target.Cursor = _prevCursor;
}
}
사용법은 다음과 같습니다. 이 사용법은 프로그램이 이상을 던질 수 있음을 예상하기 위해서입니다.
using (new AutoWaitCursor(this))
{
...
throw new Exception();
}
코드와 같이 이상을 던져도 커서가 사이의 상태로 회복됩니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.