Friday, November 6, 2009

C# : Show all assemblies loaded

using System;
using System.Text;
using System.Reflection;

namespace AssemblyListing
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain MyDomain = AppDomain.CurrentDomain;
            Assembly[] AssembliesLoaded = MyDomain.GetAssemblies();

 
            foreach (Assembly MyAssembly in AssembliesLoaded)
            {
                Console.WriteLine("Loaded: {0}", MyAssembly.FullName);
            }
        }
    }
}

C# Read Windows Logon User Name in WMI

Using the namespace System.Management,
we can easily read the Windows Logon User name.

The WMI (Windows Media Instrumentation)
queries are very similar with the SQL queries.

The sample code below written in C# reads the logon user name.

using System.Management;

public static string logonUser()
{
string _user = string.Empty;
ConnectionOptions co = new ConnectionOptions();
System.Management.ManagementScope ms
= new System.Management.ManagementScope("\" + "localhost" + "rootcimv2", co);

System.Management.ObjectQuery oq =
new System.Management.ObjectQuery("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher query =
new ManagementObjectSearcher(ms, oq);

ManagementObjectCollection queryCollection;
queryCollection = query.Get();

foreach (ManagementObject mo in queryCollection)
{
_userl = mo["UserName"].ToString();
}

char[] charSeparators = new char[] { '' };

int deger = _user.Split(charSeparators, StringSplitOptions.None).Length;
_user= _user.Split(charSeparators, StringSplitOptions.None)[deger - 1];

return _user;
}

Will return the Windows Logon User name. Many other WMI queries are available.

C# : Number Validation With Regular Expression

In order to check whether an input is a valid number or not,
regular expressions
are very easy to use to validate the input value.

The sample function below show how to check if the input is number or not, code is in C#.


using System.Text.RegularExpressions;

public static bool IsItNumber(string inputvalue)
{
Regex isnumber = new Regex("[^0-9]");
return !isnumber.IsMatch(inputvalue);
}

IsItNumber("2"); will return true;
 

IsItNumber("A"); will return false;

C# The process cannot access the file because it is being used by another process

The process cannot access the file because it is being used by another process.
This error message is mostly comes up,
when you try to access a file which is opened by another process.

You may open an image file in one of your form in a picturebox with using ImageFromFile or something.
I mostly use memorystream to open an image.
After read it in byte[] write it into a stream and close it.

You can check whether a file is being used or not with a simple function.
Try to open a file with none share.

 
public bool IsFileUsedbyAnotherProcess(string filename)
 {
 try
 {
  File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (System.IO.IOException exp)
{ 
return true;
}
return false;

}

This function will return true if
the file because it is being used by another process or not.

C# How To Get system IP Address

To get the IP address of the local machine in C#,
using system.net
namespace.

From IPHostEntry class, we get the list in a string array.

 using System.Net;

Private string GetIP()
{
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();

IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

IPAddress[] addr = ipEntry.AddressList;

return addr[addr.Length-1].ToString();

}

C# Event Log Write To EventLog Entry

Write to event log in C#
  • Add reference using System.Diagnostics to your project
  • Check whether the source exits or not.
  • If not create event source.
  • Create an EventLog object.
  • Set its event source.
  • Write the entry into event source.
C# sample source code is below;

using System.Diagnostics;

private void WriteToEventLog(string message)
{
string cs = "Your Source Name";
EventLog elog = new EventLog();

if (!EventLog.SourceExists(cs))
{
EventLog.CreateEventSource(cs, cs);
}

elog.Source = cs;
elog.EnableRaisingEvents = true;
elog.WriteEntry(message);
}

C# : Textbox autoscroll

textbox1.SelectionStart = textbox1.Text.Length;
textbox1.ScrollToCaret();
textbox1.Refresh();