Skip to content

Instantly share code, notes, and snippets.

View SamKr's full-sized avatar
🤸
Tinkering

Sam SamKr

🤸
Tinkering
  • Netherlands
  • 05:43 (UTC +02:00)
View GitHub Profile
@SamKr
SamKr / IterateString.cs
Last active March 12, 2019 10:15
Iterate through multiline string, checking for null
if (!string.IsNullOrEmpty(multiLineString))
{
using (var reader = new StringReader(multiLineString))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
@SamKr
SamKr / UppercaseWords.cs
Created March 12, 2019 10:15
Change the first letter of every word into uppercase, lowercasing everything else
internal static string UppercaseWords(string value)
{
if (string.IsNullOrEmpty(value)) return value;
value = value.ToLower();
var array = value.ToCharArray();
if (array.Length >= 1)
{
if (char.IsLower(array[0]))
{
@SamKr
SamKr / HdLogo.cs
Created April 5, 2019 09:00
Creates the HDServices logo as ASCII for console applications
internal class HdLogo
{
private static string _hdLogo = "";
internal static string GetLogo()
{
if (string.IsNullOrEmpty(_hdLogo)) Initialise();
return _hdLogo;
}
@SamKr
SamKr / InvokeReturnValue.cs
Last active June 27, 2019 09:22
Invoke a method (if GUI hook is required) and get its return value
if (object.InvokeRequired) return (bool)object.Invoke(new Func<bool>(() => FunctionName(optionalParameter)));
@SamKr
SamKr / ProcessOwner.cs
Last active June 27, 2019 09:22
Get the owner of a process, without using slow WMI calls
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
internal static string GetProcessUser(Process process, bool includeDomain = false)
{
var processHandle = IntPtr.Zero;
try
@SamKr
SamKr / Monitor.cs
Created July 3, 2019 08:51
Use perf counters to monitor a process' CPU/mem usage
using System.Diagnostics;
var counters = new List<PerformanceCounter>();
using (var proc = Process.GetCurrentProcess())
{
var processorTimeCounter = new PerformanceCounter("Process", "% Processor Time", proc.ProcessName);
processorTimeCounter.NextValue();
counters.Add(processorTimeCounter);
@SamKr
SamKr / RunOnce.cs
Last active January 6, 2020 14:02
Adds the current exec to runonce
const string userRoot = "HKEY_CURRENT_USER";
const string subkey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
const string keyName = userRoot + "\\" + subkey;
var location = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
var fileInfo = new FileInfo(location.AbsolutePath);
var fileLoc = fileInfo.FullName;
var fileDesc = Path.GetFileNameWithoutExtension(fileInfo.Name);
Registry.SetValue(keyName, fileDesc, fileLoc, RegistryValueKind.String);
@SamKr
SamKr / ActiveIp.cs
Last active January 6, 2020 14:03
Gets the current active IP address
using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp))
{
s.Bind(new IPEndPoint(IPAddress.Any, 0));
s.Connect("google.com", 0);
var ipaddr = s.LocalEndPoint as IPEndPoint;
var addr = ipaddr?.Address?.ToString() ?? "";
Console.WriteLine(addr);
}
@SamKr
SamKr / CheckInternet.cs
Last active January 6, 2020 14:03
Checks for an active internet connection
internal static bool CheckForInternetConnection()
{
try
{
using (var client = new WebClient())
using (client.OpenRead("http://google.com/generate_204"))
{
return true;
}
}
@SamKr
SamKr / LocalUser.cs
Last active January 6, 2020 14:02
Search for the existance of a local user
using System.DirectoryServices.AccountManagement;
using (var pc = new PrincipalContext(ContextType.Machine))
{
var up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "gebruiker2");
var userExists = (up != null);
if (userExists) Console.WriteLine("user exists");
else Console.WriteLine("user not found");
}