c#常用代码

随机密码

using System;
using System.Security.Cryptography;

namespace ArLi.CommonPrj
{
    public sealed class RandomStr
    {
        /********
        * Const and Function
        * ********/
        private static readonly int defaultLength = 8;

        private static int GetNewSeed()
        {
            byte[] rndBytes = new byte[4];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(rndBytes);
            return BitConverter.ToInt32(rndBytes, 0);
        }

        /********
        * getRndCode of all char .
        * ********/
        private static string BuildRndCodeAll(int strLen)
        {
            System.Random RandomObj = new System.Random(GetNewSeed());
            string buildRndCodeReturn = null;
            for (int i = 0; i < strLen; i++)
            {
                buildRndCodeReturn += (char)RandomObj.Next(33, 125);
            }
            return buildRndCodeReturn;
        }

        public static string GetRndStrOfAll()
        {
            return BuildRndCodeAll(defaultLength);
        }

        public static string GetRndStrOfAll(int LenOf)
        {
            return BuildRndCodeAll(LenOf);
        }

        /********
        * getRndCode of only .
        * ********/
        private static string sCharLow = "abcdefghijklmnopqrstuvwxyz";
        private static string sCharUpp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private static string sNumber = "0123456789";

        private static string BuildRndCodeOnly(string StrOf, int strLen)
        {
            System.Random RandomObj = new System.Random(GetNewSeed());
            string buildRndCodeReturn = null;
            for (int i = 0; i < strLen; i++)
            {
                buildRndCodeReturn += StrOf.Substring(RandomObj.Next(0, StrOf.Length - 1), 1);
            }
            return buildRndCodeReturn;
        }

        public static string GetRndStrOnlyFor()
        {
            return BuildRndCodeOnly(sCharLow + sNumber, defaultLength);
        }

        public static string GetRndStrOnlyFor(int LenOf)
        {
            return BuildRndCodeOnly(sCharLow + sNumber, LenOf);
        }

        public static string GetRndStrOnlyFor(bool bUseUpper, bool bUseNumber)
        {
            string strTmp = sCharLow;
            if (bUseUpper) strTmp += sCharUpp;
            if (bUseNumber) strTmp += sNumber;

            return BuildRndCodeOnly(strTmp, defaultLength);
        }

        public static string GetRndStrOnlyFor(int LenOf, bool bUseUpper, bool bUseNumber)
        {
            string strTmp = sCharLow;
            if (bUseUpper) strTmp += sCharUpp;
            if (bUseNumber) strTmp += sNumber;

            return BuildRndCodeOnly(strTmp, LenOf);
        }
    }
}

回复人: ArLi2003(阿利,失业+失恋 努力中) ( ) 信誉:100 2003-4-25 0:52:21 得分:0

文件夹选择对话框

using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections;

namespace ArLi.CommonPrj
{
    #region how use this?
    /*
    FolderBrowser fbObj = new FolderBrowser();
    fbObj.Title = "Select a Folder";
    fbObj.Flags = 
        BrowseFlags.BIF_NEWDIALOGSTYLE|
        BrowseFlags.BIF_EDITBOX|
        BrowseFlags.BIF_STATUSTEXT;
    DialogResult result = fbObj.ShowFolderBrowser();
    if (result == DialogResult.OK ) {
        MessageBox.Show(fbObj.DirectoryPath);
    }
    */
    #endregion

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    [ComVisible(true)]
    public class BROWSEINFO
    {
        public IntPtr hwndOwner;
        public IntPtr pidlRoot;
        public IntPtr pszDisplayName;
        public string lpszTitle;
        public int ulFlags;
        public IntPtr lpfn;
        public IntPtr lParam;
        public int iImage;
    }

    [Flags, Serializable]
    public enum BrowseFlags
    {
        BIF_DEFAULT = 0x0000,
        BIF_BROWSEFORCOMPUTER = 0x1000,
        BIF_BROWSEFORPRINTER = 0x2000,
        BIF_BROWSEINCLUDEFILES = 0x4000,
        BIF_BROWSEINCLUDEURLS = 0x0080,
        BIF_DONTGOBELOWDOMAIN = 0x0002,
        BIF_EDITBOX = 0x0010,
        BIF_NEWDIALOGSTYLE = 0x0040,
        BIF_NONEWFOLDERBUTTON = 0x0200,
        BIF_RETURNFSANCESTORS = 0x0008,
        BIF_RETURNONLYFSDIRS = 0x0001,
        BIF_SHAREABLE = 0x8000,
        BIF_STATUSTEXT = 0x0004,
        BIF_UAHINT = 0x0100,
        BIF_VALIDATE = 0x0020,
        BIF_NOTRANSLATETARGETS = 0x0400,
    }

    public class API
    {
        [DllImport("shell32.dll", PreserveSig = true, CharSet = CharSet.Auto)]
        public static extern IntPtr SHBrowseForFolder(BROWSEINFO bi);

        [DllImport("shell32.dll", PreserveSig = true, CharSet = CharSet.Auto)]
        public static extern bool SHGetPathFromIDList(IntPtr pidl, IntPtr pszPath);

        [DllImport("shell32.dll", PreserveSig = true, CharSet = CharSet.Auto)]
        public static extern int SHGetSpecialFolderLocation(IntPtr hwnd, int csidl, ref IntPtr ppidl);
    }

    public class FolderBrowser
    {
        private string m_strDirectoryPath;
        private string m_strTitle;
        private string m_strDisplayName;
        private BrowseFlags m_Flags;
        public FolderBrowser()
        {
            m_Flags = BrowseFlags.BIF_DEFAULT;
            m_strTitle = "";
        }

        public string DirectoryPath
        {
            get { return this.m_strDirectoryPath; }
        }

        public string DisplayName
        {
            get { return this.m_strDisplayName; }
        }

        public string Title
        {
            set { this.m_strTitle = value; }
        }

        public BrowseFlags Flags
        {
            set { this.m_Flags = value; }
        }

        public DialogResult ShowFolderBrowser()
        {
            BROWSEINFO bi = new BROWSEINFO();
            bi.pszDisplayName = IntPtr.Zero;
            bi.lpfn = IntPtr.Zero;
            bi.lParam = IntPtr.Zero;
            bi.lpszTitle = "Select Folder";
            IntPtr idListPtr = IntPtr.Zero;
            IntPtr pszPath = IntPtr.Zero;
            try
            {
                if (this.m_strTitle.Length != 0)
                {
                    bi.lpszTitle = this.m_strTitle;
                }
                bi.ulFlags = (int)this.m_Flags;
                bi.pszDisplayName = Marshal.AllocHGlobal(256);

                idListPtr = API.SHBrowseForFolder(bi);

                if (idListPtr == IntPtr.Zero)
                {
                    return DialogResult.Cancel;
                }

                pszPath = Marshal.AllocHGlobal(256);
                bool bRet = API.SHGetPathFromIDList(idListPtr, pszPath);

                m_strDirectoryPath = Marshal.PtrToStringAuto(pszPath);
                this.m_strDisplayName = Marshal.PtrToStringAuto(bi.pszDisplayName);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                return DialogResult.Abort;
            }
            finally
            {
                if (idListPtr != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(idListPtr);
                }
                if (pszPath != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pszPath);
                }
                if (bi != null)
                {
                    Marshal.FreeHGlobal(bi.pszDisplayName);
                }
            }
            return DialogResult.OK;
        }
    }
}

获取资源文件内容

using System;
using System.Reflection;
using System.Resources;

namespace ArLi.CommonPrj {
    internal class getResPrj {
        internal static object GetResOf(string resFullName,string resItemName) {
            Assembly myAssem = Assembly.GetEntryAssembly();
            ResourceManager rm = new ResourceManager(resFullName,myAssem);
            return rm.GetObject(resItemName);
        }
    }
}

回复人: ArLi2003(阿利,失业+失恋 努力中) ( ) 信誉:100 2003-4-25 0:53:01 得分:0

获取硬盘序列号

using System;
using System.Runtime.InteropServices;

namespace ArLi.CommonPrj
{
    #region how use this?
    /*
    string sVol = GetVolOf("C");
    */
    #endregion

    public class getvol
    {
        [DllImport("kernel32.dll")]
        private static extern int GetVolumeInformation(
            string lpRootPathName,
            string lpVolumeNameBuffer,
            int nVolumeNameSize,
            ref int lpVolumeSerialNumber,
            int lpMaximumComponentLength,
            int lpFileSystemFlags,
            string lpFileSystemNameBuffer,
            int nFileSystemNameSize
        );

        public static string GetVolOf(string drvID)
        {
            const int MAX_FILENAME_LEN = 256;
            int retVal = 0;
            int a = 0;
            int b = 0;
            string str1 = null;
            string str2 = null;

            int i = GetVolumeInformation(
                drvID + @":\",
                str1,
                MAX_FILENAME_LEN,
                ref retVal,
                a,
                b,
                str2,
                MAX_FILENAME_LEN
            );

            return retVal.ToString("x");
        }
    }
}

回复人: ArLi2003(阿利,失业+失恋 努力中) ( ) 信誉:100 2003-4-25 0:53:36 得分:0

禁止程序重复运行限制

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;

namespace ArLi.CommonPrj
{
    public class one_instance_Check
    {
        public one_instance_Check()
        {
        }

        #region how use this?
        /*
        using ArLi.CommonPrj;

        if (one_instance_Check.goCheck("Process Exist !")) {
            Application.Run (new Form1());
        }
        */
        #endregion

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        private const int WS_SHOWNORMAL = 1;

        public static bool GoCheck(string waringMessage_ifExist)
        {
            Process instance = RunningInstance();
            if (instance == null)
            {
                return true;
            }
            else
            {
                if (waringMessage_ifExist != null)
                {
                    System.Windows.Forms.MessageBox.Show(
                        null,
                        waringMessage_ifExist,
                        System.Windows.Forms.Application.ProductName.ToString(),
                        System.Windows.Forms.MessageBoxButtons.OK,
                        System.Windows.Forms.MessageBoxIcon.Exclamation
                    );

                }
                HandleRunningInstance(instance);
                return false;
            }
        }

        private static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            //Loop through the running processes in with the same name
            foreach (Process process in processes)
            {
                //Ignore the current process
                if (process.Id != current.Id)
                {
                    //Make sure that the process is running from the exe file.
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
                    current.MainModule.FileName)
                    {
                        //Return the other process instance.
                        return process;
                    }
                }
            }

            //No other instance was found, return null.
            return null;
        }

        private static void HandleRunningInstance(Process instance)
        {
            //Make sure the window is not minimized or maximized
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);

            //Set the real intance to foreground window
            SetForegroundWindow(instance.MainWindowHandle);
        }
    }
}

回复人: ArLi2003(阿利,失业+失恋 努力中) ( ) 信誉:100 2003-4-25 0:53:47 得分:0

文件操作

using System;
using System.IO;

namespace ArLi.CommonPrj
{
    internal class FileOp
    {
        internal static string ReadFileOf(string fileFullName)
        {
            string fileBody = "";
            try
            {
                FileStream ObjFile = new FileStream(fileFullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader sw = new StreamReader(ObjFile, System.Text.Encoding.Default);
                fileBody = sw.ReadToEnd();
                sw.Close();
                ObjFile.Close();
            }
            catch (Exception e)
            {
                fileBody = e.Message.ToString();
            }
            return fileBody;
        }
        internal static string SaveFileOf(string fileFullName, string fileBody)
        {
            try
            {
                FileStream ObjFile = new FileStream(fileFullName, FileMode.Create, FileAccess.Write, FileShare.Read);
                StreamWriter sw = new StreamWriter(ObjFile, System.Text.Encoding.Default);
                sw.Write(fileBody);
                sw.Close();
                ObjFile.Close();
                return null;
            }
            catch (Exception e)
            {
                return e.Message.ToString();
            }
        }
    }
}

回复人: ArLi2003(阿利,失业+失恋 努力中) ( ) 信誉:100 2003-4-25 0:54:44 得分:0

播放声音

using System;
using System.Runtime.InteropServices;

namespace ArLi.CommonPrj
{
    internal class sndPlay
    {
        [DllImport("winmm.dll", EntryPoint = "PlaySound")]
        internal static extern bool PlaySound(ref Byte snd, IntPtr hmod, uint fdwSound);

        #region how use this ?
        /* 
        //get wav byte[] from ResourceFile to sound
        ArLi.CommonPrj.sndPlay.sound=(System.Byte[])ArLi.CommonPrj.getResPrj.getResOf("namespace.ResourceFileName","ResourceItemName");
        //play of:
        ArLi.CommonPrj.sndPlay.PlaySound(ref ArLi.CommonPrj.sndPlay.sound[0],IntPtr.Zero,(uint)ArLi.CommonPrj.sndPlay.PlayingFlags.SND_MEMORY | (uint)ArLi.CommonPrj.sndPlay.PlayingFlags.SND_ASYNC);
        //stop of;
        ArLi.CommonPrj.sndPlay.sound = new System.Byte[]{0};
        ArLi.CommonPrj.sndPlay.PlaySound(ref ArLi.CommonPrj.sndPlay.sound[0],IntPtr.Zero,(uint)ArLi.CommonPrj.sndPlay.PlayingFlags.SND_MEMORY | (uint)ArLi.CommonPrj.sndPlay.PlayingFlags.SND_PURGE | (uint)ArLi.CommonPrj.sndPlay.PlayingFlags.SND_NODEFAULT);
        */
        #endregion

        [DllImport("winmm.dll", EntryPoint = "mciSendString")]
        internal static extern int mciSendString(string lpstrCommand, string lpstrReturnstring, int uReturnLength, int hwndCallback);

        #region how use this ?
        /*
        int i = sndPlay.mciSendString(@"play D:\Media\Midi\bg1.mid",null,0,0);
        int i = sndPlay.mciSendString(@"close D:\Media\Midi\bg1.mid",null,0,0);
        */
        #endregion

        internal static System.Byte[] sound = null;
        internal enum PlayingFlags : uint
        {
            SND_SYNC = 0x00,
            SND_ASYNC = 0x01,
            SND_NODEFAULT = 0x02,
            SND_MEMORY = 0x04,
            SND_ALIAS = 0x010000,
            SND_FILENAME = 0x020000,
            SND_RESOURCE = 0x040004,
            SND_ALIAS_ID = 0x0110000,
            SND_ALIAS_START = 0,
            SND_LOOP = 0x08,
            SND_NOSTOP = 0x010,
            SND_VALID = 0x01F,
            SND_NOWAIT = 0x02000,
            SND_PURGE = 0x40
        }
    }
}

补充:SND_PURGE 参数很重要,很多人漏掉了,可以用来中止一些用sndplay 循环播放的声音

回复人: ArLi2003(阿利,失业+失恋 努力中) ( ) 信誉:100 2003-4-25 0:55:02 得分:0

加系统菜单

using System;
using System.Runtime.InteropServices;

namespace ArLi.CommonPrj
{
    #region how use this?
    /*
    * append this to Form Code body
    *
    using ArLi.CommonPrj;

    internal const Int32 aboutID = 1000;
    protected override void WndProc(ref Message m) {
    if(m.Msg == CommonPrj.sysMenu.WM_SYSCOMMAND)
    switch(m.WParam.ToInt32()) {
    case aboutID :
    fm_About Obj = new fm_About();
    Obj.ShowDialog(this);
    return;
    default:
    break;
    }
    base.WndProc(ref m);
    }
    *
    * appendmenu on form_load
    *
    //add menuLine 
    sysMenu.AddMenu(this.Handle,0,null);
    //add menuItem
    sysMenu.AddMenu(this.Handle,IDM_ABOUT,"About ...");
    */
    #endregion

    internal class sysMenu
    {
        internal sysMenu() { }

        [DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

        [DllImport("user32.dll")]
        private static extern bool AppendMenu(IntPtr hMenu, Int32 wFlags, Int32 wIDNewItem, string lpNewItem);

        internal const Int32 WM_SYSCOMMAND = 0x112;
        internal const Int32 MF_SEPARATOR = 0x800;
        internal const Int32 MF_STRING = 0x0;

        internal static void AddMenu(IntPtr handleOf, Int32 menuID, string menuStrOf)
        {
            IntPtr sysMenuHandle = GetSystemMenu(handleOf, false);
            if (menuStrOf == null)
            {
                AppendMenu(sysMenuHandle, MF_SEPARATOR, menuID, string.Empty);
            }
            else
            {
                AppendMenu(sysMenuHandle, MF_STRING, menuID, menuStrOf);
            }
        }
    }
}

回复人: ArLi2003(阿利,失业+失恋 努力中) ( ) 信誉:100 2003-4-25 0:56:03 得分:0

以下是程序

此为资源文件生成器,支持二进制

using System;
using System.IO;
using System.Drawing;
using System.Resources;
using System.Reflection;
using System.Windows.Forms;

[assembly: System.Reflection.AssemblyVersion("1.2.*")]
[assembly: System.Reflection.AssemblyTitle("Resource Build")]
[assembly: System.Reflection.AssemblyDescription("Resource with Binary")]
[assembly: System.Reflection.AssemblyConfiguration("")]
[assembly: System.Reflection.AssemblyCompany("ArLi")]
[assembly: System.Reflection.AssemblyProduct("Resource Build")]
[assembly: System.Reflection.AssemblyCopyright("ArLi build on C#")]
[assembly: System.Reflection.AssemblyTrademark("")]
[assembly: System.Reflection.AssemblyCulture("")]

class resAdd
{
    private static AssemblyCopyrightAttribute objCopyright = (AssemblyCopyrightAttribute)AssemblyCopyrightAttribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCopyrightAttribute));
    private static string myCopyright = objCopyright.Copyright.ToString();
    private static string myExeName = new FileInfo(Application.ExecutablePath).Name + " ";

    private static string mySwitch = "[Switch]:\n" +
        "/fn,fileFullName\t\tResource FileName(no Extension)\n" +
        "/img,itemName,fileFullName\tImage Type Add of Filename \n\t\t\t\t(support gif/png/jpg/bmp/ico)\n" +
        "/ico,itemName,fileFullName\tIcon Type Add of Filename \n" +
        "/bin,itemName,fileFullName\tBinary Type Add of FileName";
    private static string myExemple = "[Exemple]: Create c:\\tst.resources\n" +
        myExeName +
        "/fn,c:\\tst " +
        "/bin,wav1,wav1.wav " +
        "/bin,wav2,c:\\wav2.wav " +
        "/img,img1,bmp1.bmp" +
        "\n" + myExeName + "/fn,c:\\tst /bin,wav1,\"c:\\winnt\\media\\The Microsoft Sound.wav\"";

    [STAThread]
    public static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            if (args[0] == "/?")
            {
                ShowHelp(null);
            }
            else
            {
                string[] filenameOf = args[0].Split(',');
                if (filenameOf[0] == "/fn" && filenameOf.Length >= 2)
                {
                    if (filenameOf[1] == "")
                    {
                        ShowHelp("u must input filename of /fn,fileFullName !");
                    }
                    else
                    {
                        string theResourcesFileName = filenameOf[1] + ".resources";
                        ResourceWriter rw = new ResourceWriter(theResourcesFileName);

                        for (int i = 1; i < args.Length; i++)
                        {
                            string[] addBody = args[i].Split(',');
                            if (addBody.Length < 3)
                            {
                                Console.WriteLine("Invalid switch on: " + args[i]);
                            }
                            else
                            {
                                FileInfo ObjFile = new FileInfo(addBody[2]);
                                if (!ObjFile.Exists)
                                {
                                    Console.WriteLine("File " + ObjFile.FullName + " no Exists!!! skip this.");
                                }
                                else
                                {
                                    switch (addBody[0].ToUpper())
                                    {
                                        case "/IMG":
                                            ImageAdd(rw, addBody[1], ObjFile.FullName);
                                            Console.WriteLine("append Type:Image of " + addBody[1] + " (" + addBody[2] + ")");
                                            break;
                                        case "/ICO":
                                            IconAdd(rw, addBody[1], ObjFile.FullName);
                                            Console.WriteLine("append Type:Icon of " + addBody[1] + " (" + addBody[2] + ")");
                                            break;
                                        case "/BIN":
                                            BinaryAdd(rw, addBody[1], ObjFile.FullName);
                                            Console.WriteLine("append Type:Binary of " + addBody[1] + " (" + addBody[2] + ")");
                                            break;
                                        default:
                                            ShowHelp("u must input resources type !");
                                            break;
                                    }
                                }
                            }
                        }
                        Console.WriteLine("\nbuild of " + theResourcesFileName + " complete.");
                        rw.Generate();
                    }
                }
                else
                {
                    ShowHelp("need filename of /fn,fileFullName !");
                }
            }
        }
        else
        {
            ShowHelp(null);
            Console.WriteLine("\nPress Enter to end ..");
            Console.Read();
        }
    }

    private static void ShowHelp(string ErrMsg)
    {
        Version PrjVer = new Version(Application.ProductVersion);

        Console.WriteLine("" + Application.ProductName.ToString() + " v" + PrjVer.Major.ToString() 
            + "." + PrjVer.Minor.ToString() + "." + PrjVer.Build.ToString() +
            " Studio: " + Application.CompanyName + " Copyright: " + myCopyright + "\n");

        if (ErrMsg != null) { Console.WriteLine("Waring !!\n" + ErrMsg + "\n"); }

        Console.WriteLine(myExemple + "\n\n" + mySwitch);
    }

    private static void BinaryAdd(ResourceWriter rw, string itemnameOf, string filenameOf)
    {
        try
        {
            FileStream fs = new FileStream(filenameOf, FileMode.Open, FileAccess.Read);
            int byteLength = (int)fs.Length;
            byte[] wf = new byte[byteLength];
            fs.Read(wf, 0, byteLength);
            fs.Close();

            rw.AddResource(itemnameOf, wf);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void ImageAdd(ResourceWriter rw, string itemnameOf, string filenameOf)
    {
        try
        {
            Image b = Image.FromFile(filenameOf);
            rw.AddResource(itemnameOf, b);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void IconAdd(ResourceWriter rw, string itemnameOf, string filenameOf)
    {
        try
        {
            Icon b = new Icon(filenameOf);
            rw.AddResource(itemnameOf, b);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

回复人: ArLi2003(阿利,失业+失恋 努力中) ( ) 信誉:100 2003-4-25 0:57:46 得分:0

程序,我以前有个习惯不使用资源而是将内容二进制打进程序

直接使用 byte[] bgSound = new byte[]{....} //此为声音文件二进制,原来是用vc 现在特用c# 重写了一个

using System;
using System.IO;
//using System.Drawing;
//using System.Resources;
using System.Reflection;
using System.Windows.Forms;
using System.Text.RegularExpressions;

[assembly: System.Reflection.AssemblyVersion("1.5.*")]
[assembly: System.Reflection.AssemblyTitle("string Build")]
[assembly: System.Reflection.AssemblyDescription("System.byte[] to string")]
[assembly: System.Reflection.AssemblyConfiguration("")]
[assembly: System.Reflection.AssemblyCompany("ArLi")]
[assembly: System.Reflection.AssemblyProduct("string Build")]
[assembly: System.Reflection.AssemblyCopyright("ArLi build on C#")]
[assembly: System.Reflection.AssemblyTrademark("")]
[assembly: System.Reflection.AssemblyCulture("")]

class resAdd {
    private static AssemblyCopyrightAttribute objCopyright = (AssemblyCopyrightAttribute)AssemblyCopyrightAttribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),typeof(AssemblyCopyrightAttribute));
    private static string myCopyright = objCopyright.Copyright.ToString();
    private static string myExeName = new FileInfo(Application.ExecutablePath).Name + " ";

    private static string myHelpBody = "" + "[Syntax]:\n" + myExeName + "formFile variableName toFile \tsave string to file\n" +
        myExeName + "formFile variableName /copy \tcopy string to clipboard.\n" +
        myExeName + "formFile variableName /copy /s \tcopy string & show stats.\n\n" +
        "[Exemple]:\n" + myExeName + "c:\\1.ico ico_1 /copy /s";

    [STAThread]
    public static void Main(string[] args) {
        if (args.Length>2) {
            if(args[0] == "/?") {
                ShowHelp(null);
            } else {
                try{
                    FileInfo fi = new FileInfo(args[0]);
                    Match MatchVariableName = Regex.Match(args[1],@"\b([a-zA-Z]\w*)",RegexOptions.IgnoreCase|RegexOptions.IgnorePatternWhitespace|RegexOptions.ExplicitCapture);
                    string variableName = MatchVariableName.ToString();
                    if (args[1].Substring(0,1) == "/"){
                        Console.WriteLine("don't forget VariableName!!!");
                    }
                    else if (! fi.Exists){
                        Console.WriteLine("File " + fi.FullName + " no Exists!!!");
                    }
                    else if (variableName == ""){
                        Console.WriteLine("invalid variableName!!");
                    }
                    else {
                        FileStream fs = new FileStream(fi.FullName,FileMode.Open, FileAccess.Read);
                        int byteLength = (int)fs.Length;
                        byte[] wf = new byte[byteLength];
                        fs.Read(wf,0,byteLength);
                        fs.Close();
                        fs = null;

                        int i = 0;
                        byte iCr = 0;
                        bool ShowStats = (args.Length>3 && args[3] == "/s");

                        string s = "System.Byte[] " + variableName + " = new System.Byte[] {";
                        string sp = new string(' ',byteLength.ToString().Length);

                        Console.Write("Poc " + s + "" + byteLength.ToString() + " byte} ...\nuse CTRL+Break can stop ...\n");

                        s += "\r\n";

                        if (ShowStats){
                            while(i < byteLength){
                                s += wf[i] + ",";
                                if (iCr == 25){
                                    s += "\r\n";
                                    iCr=0;
                                }
                                i++;
                                iCr++;
                                Console.Write("\r" + i + sp);
                            }
                        }else{
                            while(i < byteLength){
                                s += wf[i] + ",";
                                if (iCr == 25){
                                    s += "\r\n";
                                    iCr=0;
                                }
                                i++;
                                iCr++;
                            }
                        }

                        s = s.Remove(s.Length-1,1) + "\r\n};";
                        s = "\t#region System.Byte[] " + variableName + " = new System.Byte[] {...}\r\n" + s + "\r\n\t#endregion";

                        if (args[2] == "/copy") {
                            Clipboard.SetDataObject(s,true);
                        }else{
                            FileInfo ObjFile = new FileInfo(args[2]);
                            StreamWriter sw = ObjFile.CreateText();
                            sw.Write(s);
                            sw.Close();
                        }
                        Console.WriteLine("\rdone.. ^o^");
                    }
                } catch (Exception e){
                    Console.WriteLine(e.Message.ToString());
                }
            }
        } else {
            ShowHelp(null);
            Console.WriteLine("\nPress Enter to end ..");
            Console.Read();
        }
    }

    private static void ShowHelp(string ErrMsg) {
        Version PrjVer = new Version(Application.ProductVersion);

        Console.WriteLine("" + Application.ProductName.ToString() + " v" + PrjVer.Major.ToString() 
            + "." + PrjVer.Minor.ToString() + "." + PrjVer.Build.ToString() + " Studio: " 
            + Application.CompanyName + " Copyright: " + myCopyright + "\n");

        if (ErrMsg != null){Console.WriteLine("Waring !!\n" + ErrMsg + "\n");}

        Console.WriteLine(myHelpBody);
    }
}
Contributors: FHL