Click here to Skip to main content
15,888,293 members
Articles / Desktop Programming / Windows Forms

Listing and Working with Files in Archives

Rate me:
Please Sign up or sign in to vote.
2.86/5 (6 votes)
22 Jun 2007CPOL 32.2K   529   23  
This article describes how to use CAKE3, which is a wrapper component for many archiver DLLs,
/*
 * Created by SharpDevelop.
 * User: LYCJ
 * Date: 20/11/2006
 * Time: 22:26
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
using Cake3.Controls;

namespace Cake3
{
	/// <summary>
	/// Cakdir3.Utils
	/// </summary>
	public class Utils
	{
		#region External - Struct
		[StructLayout(LayoutKind.Sequential)]
		internal struct SHFILEINFO
		{
			public IntPtr hIcon;
			public IntPtr iIcon;
			public uint dwAttributes;
			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
			public string szDisplayName;
			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
			public string szTypeName;
		};
		internal const uint SHGFI_ICON = 0x100;
		internal const uint SHGFI_TYPENAME =0x400;
		internal const uint SHGFI_LARGEICON = 0x0; // 'Large icon
		internal const uint SHGFI_SMALLICON = 0x1; // 'Small icon
		internal const uint SHGFI_SYSICONINDEX = 16384;
		internal const uint SHGFI_USEFILEATTRIBUTES = 16;
		
		internal const string SH_OPENFILE			= "open";
		internal const string SH_EDITFILE 			= "edit";
		internal const string SH_EXPLOREFOLDER 		= "explore";
		internal const string SH_FILDINFOLDER		= "find";
		internal const string SH_PRINTFILE 			= "print";
		
		private enum ShellExecuteShowCmds
		{
			Hide = 0,
			ShowNormal,
			Normal,
			ShowMinimized,
			ShowMaximized,
			Maximize,
			ShowNoActivate,
			Show,
			Minimize,
			ShowMinNoActive,
			Showna,
			Restore,
			ShowDefault,
			Max
		};
		#endregion
		
		#region External - DllImport
		
		
		/// <summary>
		/// Get Icons that are associated with files.
		/// To use it, use (System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon));
		/// hImgSmall = SHGetFileInfo(fName, 0, ref shinfo,(uint)Marshal.SizeOf(shinfo),Win32.SHGFI_ICON |Win32.SHGFI_SMALLICON);
		/// </summary>
		[DllImport("shell32.dll")]
		internal static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes,
		                                          ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
		
		/// <summary>
		/// Shell Execute, If (Int32)retVal > 32 then success
		/// </summary>
		/// <param name="hwnd">Handle to a parent window.</param>
		/// <param name="lpOperation">Action to be performed.</param>
		/// <param name="lpFile">File or object on which to execute the specified verb.</param>
		/// <param name="lpParameters">Parameters to be passed to the application (if exe).</param>
		/// <param name="lpDirectory">Default directory. </param>
		/// <param name="nShowCmd">Specify how an application is to be displayed when it is opened.</param>
		/// <returns></returns>
		[DllImport("shell32.dll")]
		internal static extern IntPtr ShellExecute(IntPtr hwnd,
		                                         [MarshalAs(UnmanagedType.LPStr)]String lpOperation,
		                                         [MarshalAs(UnmanagedType.LPStr)]String lpFile,
		                                         [MarshalAs(UnmanagedType.LPStr)]String lpParameters,
		                                         [MarshalAs(UnmanagedType.LPStr)]String lpDirectory,
		                                         Int32 nShowCmd);
		
		
		[DllImport("user32.dll")]
		internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

		[DllImport("user32.dll")]
		internal static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, UIntPtr wParam,IntPtr lParam);

		[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
		internal static extern uint RegisterWindowMessage(string lpString);
				
		//From GotDotNet User Sample
		[DllImport("kernel32.dll")]
		static extern uint GetLongPathName(string shortname, StringBuilder
			longnamebuff, uint buffersize);

		[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
		public static extern int GetShortPathName(
			[MarshalAs(UnmanagedType.LPTStr)]
			string path,
			[MarshalAs(UnmanagedType.LPTStr)]
			StringBuilder shortPath,
			int shortPathLength);				
		#endregion
		
		#region Conversion - Slash
		/// <summary>
		/// Add a slash "\" to end of input if not exists.
		/// </summary>
		public static string AppendSlash(string input)
		{			
			if (input.EndsWith(@"\")) { return input; }
			else
			{ return input + @"\"; }
		}
		
		/// <summary>
		/// Add a slash "\" to front of input if not exists.
		/// </summary>
		public static string AppendFrontSlash(string input)
		{
			if (input.StartsWith(@"\")) { return input; }
			else
			{ return @"\" + input; }
		}
		
		/// <summary>
		/// Remove a slash "\" from the front of input if exists.
		/// </summary>		
		public static string RemoveFrontSlash(string input)
		{
			if (input.StartsWith(@"\")) { return input.Substring(1, input.Length - 1); }
			else
			if (input.StartsWith(@"/")) { return input.Substring(1, input.Length - 1); }
			else
			{ return input; }
		}
		
		/// <summary>
		/// Remove slash end of input.
		/// </summary>
		public static string RemoveSlash(string input)
		{
			if (input.EndsWith(@"\")) { return input.Substring(0, input.Length - 1); }
			else
			{ return input; }
		}
		/// <summary>
		/// Return filename.
		/// </summary>
		public static string ExtractFileName(string input)
		{
			Int32 idx = input.LastIndexOfAny((",\\;").ToCharArray())+1;
			if (idx == 0)
				return input;
			return input.Substring(idx);
		}
		
		/// <summary>
		/// Return the first directory found from the input. 
		/// (E.g. ExtractFirstDir("\temp\1\2",0) will return "Temp")
		/// </summary>
		public static string ExtractFirstDir(string input, Int32 startIndex)
		{
			if (input.Length < startIndex)
				return "";
			Int32 idx = input.IndexOf('\\',startIndex);
			if (idx == -1)
				return input.Substring(startIndex);
			return input.Substring(startIndex, idx - startIndex);
		}
		
		/// <summary>
		/// Return file path.
		/// </summary>
		public static string ExtractFilePath(string input)
		{
			if (input.Length <= 1)
				return "";
			Int32 idx = input.LastIndexOfAny((",\\;").ToCharArray())+1;
			if (idx == 0)
				return input;
			return input.Substring(0,idx-1);
		}
		
		/// <summary>
		/// Return file extension.
		/// </summary>
		public static string ExtractFileExt(string input)
		{
			Int32 idx = input.LastIndexOfAny((",\\;.").ToCharArray());
			if ((idx > 0) && (input[idx] == '.'))
				return input.Substring(idx, input.Length - idx);
			return "";
		}
		
		/// <summary>
		/// Remove file extension and return the value.
		/// </summary>
		public static string RemoveFileExt(string input)
		{
			Int32 idx = input.LastIndexOfAny((",\\;.").ToCharArray());
			if ((idx > 0) && (input[idx] == '.'))
				return input.Substring(0, idx);
			return input;
		}
		
		/// <summary>
		/// Remove file drive and return the value.
		/// </summary>
		public static string RemoveFileDrive(string input)
		{			
			if (input.Length >= 3) //"C:\"
			{
				if (input.IndexOf(@":\") != -1)
				{
					return input.Substring(input.IndexOf(@":\")+2);						
				}
			}			
			return "";				
		}
		
		/// <summary>
		/// Return file drive.
		/// </summary>
		public static char GetFileDrive(string input)
		{
			if (input.Length >= 3) //"C:\"
			{
				if (input.Substring(1,2) == @":\")
				{
					return input[0];
				}
			}			
			return ' ';				
		}
		
		/// <summary>
		/// Return a common folder so that all files is under that common folder.
		/// (e.g. C:\1\2, C:\1\3 will return "C:\1")
		/// </summary>
		public static string HighestCommonFolder(string[] files)
		{
			if (files == null) return "";
			if (files.Length <= 0) return "";
			
			string retVal = Utils.ExtractFilePath(files[0]).ToLower();
			foreach (string item in files)
			{
				string path = Utils.ExtractFilePath(item).ToLower();
				
				if (retVal != path)
					if (path.IndexOf(retVal) == 0)
						retVal = path;
					else if (retVal.IndexOf(retVal) == 0)
						{ 
							//do nothing						
						}
					else 
						throw new ArgumentException("Not all file based on same relative folder!");
			}
			
			return Utils.AppendSlash(retVal);
		}
		
		#endregion
		
		#region Conversion - Kb
		/// <summary>
		/// Convert size (int) to Kb string more readable to human.
		/// </summary>
		public static string SizeInK(UInt64 size)
		{
			if (size == 0)
				return "0 kb";
			
			float sizeink = ((float)size / 1024);
			
			if (sizeink <= 999.99)
				return sizeink.ToString("#0.00") + " kb";
			
			return sizeink.ToString("###,###,###,##0") + " kb";
		}
		
		/// <summary>
		/// Convert Kb string to size (int), which is usable by computer.
		/// </summary>
		public static UInt64 KtoSize(string value)
		{
			value = value.Replace("kb","");
			value = value.Replace(",","");
			value = value.Trim();
			
			double ktosize;
			try
			{
				ktosize = Convert.ToDouble(value);
			}
			catch
			{
				ktosize = 0;
			}
			
			return (UInt64)(ktosize * 1024);
		}


		#endregion
		
		#region Conversion - DateTime
		/// <summary>
		/// Convert a Dos datetime to Datetime.
		/// </summary>
		public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime)
		{
			int year =  iDate / 512 + 1980;
			int month = iDate % 512 / 32;
			int day = iDate % 512 % 32;
			int hour = iTime / 2048;
			int minute = iTime % 2048 / 32;
			int second = iTime % 2048 % 32 * 2;

			if (iDate == UInt16.MaxValue || month == 0 || day == 0)
			{
				year = 1980;
				month = 1;
				day = 1;
			}

			if (iTime == UInt16.MaxValue)
			{
				hour = minute = second = 0;
			}

			DateTime dt;
			try
			{
				dt = new DateTime(year, month, day, hour, minute, second);
			}
			catch
			{
				dt = new DateTime();
			}
			return dt;
		}
		
		/// <summary>
		/// Convert a Dos datetime to Datetime.
		/// </summary>
		public static DateTime DosDateToDateTime(UInt32 iTime)
		{
			return DosDateToDateTime((UInt16)(iTime / 65536),
			                         (UInt16)(iTime % 65536));
		}
		
		public static DateTime DosDateToDateTime(Int32 iTime)
		{
			return DosDateToDateTime((UInt32)iTime);
		}
		#endregion
		
		#region IO - Paths
		/// <summary>
		/// Return current path.
		/// </summary>
		public static string GetCurrentPath()
		{
			return AppendSlash(Directory.GetCurrentDirectory());
		}
		
		/// <summary>
		/// Return Desktop path.
		/// </summary>
		public static string GetDesktopPath()
		{
			return AppendSlash(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
		}
		
		/// <summary>
		/// Return Mydocument path.
		/// </summary>
		public static string GetMydocuPath()
		{
			return AppendSlash(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
		}
		/// <summary>
		/// Return Appdata path.
		/// </summary>		
		public static string GetAppdataPath()
		{
			return AppendSlash(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
		}
		
		/// <summary>
		/// Return ProgramFiles path.
		/// </summary>		
		public static string GetProgramPath()
		{
			System.Reflection.Assembly assembly;
			assembly = System.Reflection.Assembly.GetExecutingAssembly();
			if (assembly != null)
				return AppendSlash(ExtractFilePath(assembly.Location));
			else
				return AppendSlash(ExtractFilePath(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));			
		}
		
		/// <summary>
		/// Return Windows system path.
		/// </summary>		
		public static string GetSystemPath()
		{
			return AppendSlash(Environment.GetFolderPath(Environment.SpecialFolder.System));
		}
		
		/// <summary>
		/// Return Temp path.
		/// </summary>		
		public static string GetTempPath()
		{
			return AppendSlash(System.IO.Path.GetTempPath());
		}		
		/// <summary>
		/// Create a unique new temp path and return.
		/// </summary>
		public static string NewTempPath(string prefix)
		{
			string tempDir = Utils.GetTempPath() + Utils.AppendSlash(prefix);
			Int32 idx = 1;
			while (Utils.DirectoryExists(tempDir + idx.ToString() + "\\"))
				idx++;
			tempDir = tempDir + idx.ToString() + "\\";
			Utils.MakeDirectory(tempDir);
			
			return tempDir;
		}
		/// <summary>
		/// Return %Temp%\%archive%.
		/// </summary>		
		public static string GetArchiveTempPath(string archiveName)
		{
			return GetTempPath() + ExtractFileName(archiveName) + '\\';
		}
		
		/// <summary>
		/// Return whether a filename match the path.
		/// </summary>		
		public static bool MatchPath(string path, string filename, bool subdir)
		{
			if (path == "") return true;
			if (!(filename.StartsWith(path))) return false;
			if ( !subdir && (filename.LastIndexOf('\\') > path.Length)) return false;
			
			return true;
		}
		
		public static string GetShortFileName(string longName)
		{
			StringBuilder shortNameBuffer = new StringBuilder(256);
			int bufferSize = shortNameBuffer.Capacity;

			int result = GetShortPathName(longName, shortNameBuffer, bufferSize);

			return shortNameBuffer.ToString();
		}
		
		public static string GetLongFileName(string shortName)
		{
			StringBuilder longNameBuffer = new StringBuilder(256);
			uint bufferSize = (uint)longNameBuffer.Capacity;

			GetLongPathName(shortName, longNameBuffer, bufferSize);

			return longNameBuffer.ToString();
		}

		
		#endregion
		
		#region IO - FileList Polling
		/// <summary>
		/// Get a list of file in specified path.
		/// </summary>
		public static List<string> GetFileList(string path, string mask)
		{
			List<string> retVal = new List<string>();
			DirectoryInfo dirInfo = new DirectoryInfo(path);
			FileInfo[] fInfoList = dirInfo.GetFiles(mask);
			foreach (FileInfo fi in fInfoList)
			{
				retVal.Add(AppendSlash(path) + fi.Name);
			}
			return retVal;
		}
		
		/// <summary>
		/// Get a list of folder in specified foldername. (Mask supported)
		/// </summary>
		public static List<string> PollDirList(string folderName, bool subDir)
		{
			DirectoryInfo curDirInfo;
			DirectoryInfo[] dirInCurDir;			
			List<string> dirInSubDir;			
			List<string> retVal = new List<string>();			
						
			curDirInfo = new System.IO.DirectoryInfo(folderName);
			dirInCurDir = curDirInfo.GetDirectories();
			foreach (DirectoryInfo di in dirInCurDir)
			{
				string folder = AppendSlash(AppendSlash(folderName)+di.ToString());
				retVal.Add(folder);
				
				if (subDir)
				{
					dirInSubDir = PollDirList(folder, true);
					retVal.AddRange(dirInSubDir);
				}
			}
						
			return retVal;
		}
		
		/// <summary>
		/// Get a list of file in specified foldername. (Mask supported)
		/// </summary>
		public static List<string> PollFileList(string maskedName, bool subDir)
		{
			if (!maskedName.Contains("*") && !maskedName.Contains("?"))
				subDir = false;
			
			DirectoryInfo curDirInfo;
			DirectoryInfo[] dirInCurDir;
			FileInfo[] fileInCurDir;
			List<string> fileInSubDir;
			string folder, mask;
			List<string> retVal = new List<string>();
			
			mask = ExtractFileName(maskedName);
			folder = ExtractFilePath(maskedName);
			curDirInfo = new System.IO.DirectoryInfo(Utils.AppendSlash(folder));
			if (mask == "")
				mask = "*";
			fileInCurDir = curDirInfo.GetFiles(mask);
			
			foreach (FileInfo fi in fileInCurDir)
				retVal.Add(fi.FullName);
			
			if (subDir)
			{
				dirInCurDir = curDirInfo.GetDirectories();
				foreach (DirectoryInfo di in dirInCurDir)
				{
					fileInSubDir = PollFileList(AppendSlash(AppendSlash(folder)+di.ToString())+mask, true);
					retVal.AddRange(fileInSubDir);
				}
			}
			
			if ((retVal.Count == 0) && (Utils.FileExists(maskedName)))
				retVal.Add(maskedName);
			return retVal;
		}
		
		/// <summary>
		/// Return whether the specified directory exits.
		/// </summary>
		public static bool DirectoryExists(string dirName)
		{
			return System.IO.Directory.Exists(dirName);
		}
		/// <summary>
		/// Return whether the specified file exits.
		/// </summary>
		public static bool FileExists(string fileName)
		{
			return System.IO.File.Exists(fileName);
		}
		/// <summary>
		/// Return a FileInfo object of the specified file.
		/// </summary>
		public static FileInfo GetFileInfo(string fileName)
		{
			if (FileExists(fileName))
				return new System.IO.FileInfo(fileName);
			return null;
		}
		/// <summary>
		/// Return file size of the specified file.
		/// </summary>
		public static Int64 GetFileSize(string fileName)
		{
			if (FileExists(fileName))
				return new System.IO.FileInfo(fileName).Length;
			return 0;
		}
		/// <summary>
		/// Return small file icon of the specified file.
		/// </summary>
		public static Icon GetSmallFileIcon(string fileName)
		{
			SHFILEINFO shinfo = new SHFILEINFO();
			fileName = ExtractFileName(fileName);
			
			SHGetFileInfo(fileName, 0, ref shinfo,
			              (uint)Marshal.SizeOf(shinfo),Utils.SHGFI_ICON |Utils.SHGFI_SMALLICON |
			              Utils.SHGFI_SYSICONINDEX | Utils.SHGFI_USEFILEATTRIBUTES);
			return System.Drawing.Icon.FromHandle(shinfo.hIcon);
		}
		
		/// <summary>
		/// Return large file icon of the specified file.
		/// </summary>
		public static Icon GetLargeFileIcon(string fileName)
		{
			SHFILEINFO shinfo = new SHFILEINFO();
			fileName = ExtractFileName(fileName);
			
			SHGetFileInfo(fileName, 0, ref shinfo,
			              (uint)Marshal.SizeOf(shinfo),Utils.SHGFI_ICON |
			              Utils.SHGFI_SYSICONINDEX | Utils.SHGFI_USEFILEATTRIBUTES);
			return System.Drawing.Icon.FromHandle(shinfo.hIcon);
		}
		
		/// <summary>
		/// Return file type of the specified file.
		/// </summary>
		public static string GetFileType(string fileName)
		{
			SHFILEINFO shinfo = new SHFILEINFO();
			fileName = ExtractFileName(fileName);
			
			SHGetFileInfo(fileName, 0, ref shinfo,
			              (uint)Marshal.SizeOf(shinfo),SHGFI_TYPENAME |
			              Utils.SHGFI_SYSICONINDEX | Utils.SHGFI_USEFILEATTRIBUTES);
			return shinfo.szTypeName;
		}
		
		/// <summary>
		/// Return whether the specified dll exists.
		/// </summary>
		public static bool verifyDllPath(ref string dllPath)
		{
			if (dllPath == "")
				return false;
			
			if (Utils.FileExists(Utils.GetProgramPath() + dllPath))
			{
				dllPath = Utils.GetProgramPath() + dllPath;
				return true;
			}
					
			return false;
		}
		
		/// <summary>
		/// Return whether the specified dll exists.
		/// </summary>
		public static bool verifyDllPath(string dllPath)
		{
			string dummy = dllPath;
			return verifyDllPath(ref dllPath);
		}
		

		#endregion
		
		#region IO - Directory
		/// <summary>
		/// Create a directory.
		/// </summary>		
		public static void MakeDirectory(string dirName)
		{
			System.IO.Directory.CreateDirectory(dirName);
		}
		
		/// <summary>
		/// Remove a directory.
		/// </summary>		
		public static void RemoveDirectory(string dirName)
		{
			try
			{
				if (Utils.DirectoryExists(dirName))
					System.IO.Directory.Delete(dirName,true);
			}
			catch
			{
				
			}
		}
		
		/// <summary>
		/// Explore a directory in a explorer window.
		/// </summary>		
		public static void ExploreDirectory(string dirName)
		{
			ShellExecute(IntPtr.Zero, SH_EXPLOREFOLDER, dirName, "", "",
			             (Int32)ShellExecuteShowCmds.ShowNormal);
		}
		
		/// <summary>
		/// Open a directory in a explorer window.
		/// </summary>		
		public static void OpenDirectory(string dirName)
		{
			ShellExecute(IntPtr.Zero, SH_OPENFILE, dirName, "", "",
			             (Int32)ShellExecuteShowCmds.ShowNormal);
		}		
		#endregion
		
		#region IO - File
		/// <summary>
		/// Move a file.
		/// </summary>
		public static void MoveFile(string srcFile, string destFile)
		{
			if (!FileExists(srcFile)) 
				return;
			if (FileExists(destFile))
				RemoveFile(destFile);
			System.IO.File.Move(srcFile, destFile);
		}
		
		/// <summary>
		/// Remove a file.
		/// </summary>		
		public static void RemoveFile(string fileName)
		{
			if (FileExists(fileName))
				System.IO.File.Delete(fileName);
		}
		/// <summary>
		/// Copy file.
		/// </summary>
		public static void CopyFile(string srcFile, string destFile)
		{
			System.IO.File.Copy(srcFile, destFile);
		}
		/// <summary>
		/// Copy file(s) (mask allowed) to dest dir. 
		/// </summary>
		public static void CopyFileMask(string srcFileMask, string destDir, bool subDir)
		{										
			string srcDir = Utils.GetLongFileName(Utils.ExtractFilePath(srcFileMask)).ToLower();
			List<string> fileList = Utils.PollFileList(srcFileMask, subDir);
			
			foreach (string file in fileList)
			{				
				string destFile = "";
				
				if (file.ToLower().IndexOf(srcDir.ToLower()) == 0)
					destFile = destDir + file.Substring(srcDir.Length);
				else 
					destFile = destDir + file;
				
				Utils.MakeDirectory(Utils.ExtractFilePath(destFile));
				System.IO.File.Copy(file, destFile);
			}
		}
		
		#endregion
		
		#region String - Parse
		/// <summary>
		/// Parse Pchar, this function is unused.
		/// </summary>
		public static string ParsePChar(string input)
		{
			int idx = input.IndexOf('\0');
			if (idx == -1) return input;
			else return input.Substring(0, idx-1);
		}		
		#endregion
				
		#region String - Mask
		
		internal class tlLookupTag
		{
			internal tagLookup lookup;
			public Int32 foundStart;
			public Int32 foundEnd;
			
			public virtual bool Found(Int32 startIdx)
			{
				return false;
			}
			
			public virtual Int32 RequestText(string text)
			{
				return -1;
			}
			
			public virtual tlLookupTag PreviousTag()
			{
				Int32 idx = lookup.TagList.IndexOf(this);
				if (idx > 0)
					return lookup.TagList[idx-1];
				return null;
			}
			
			public tlLookupTag(tagLookup aLookup)
			{
				lookup = aLookup;
			}
		}
		
		internal class tlLookupText : tlLookupTag
		{
			string targetText;
			public override bool Found(Int32 startIdx)
			{
				if (startIdx >= lookup.Text.Length)
					foundStart = -1;
				else foundStart = lookup.Text.IndexOf(targetText,startIdx+1);
				
				if ((foundStart == -1) && (PreviousTag() != null))
					foundStart = PreviousTag().RequestText(targetText);
				
				bool retVal = (foundStart != -1);
				
				if (retVal)
					foundEnd = foundStart + targetText.Length;
				else
					foundEnd = -1;
				
				return retVal;
			}
			
			public tlLookupText(tagLookup aLookup, string aTargetText) : base(aLookup)
			{
				targetText = aTargetText;
			}
		}
		
		internal class tlLookupMask : tlLookupTag
		{
			public override bool Found(Int32 startIdx)
			{
				foundStart = startIdx + 1;
				foundEnd = lookup.Text.Length; //13-06-07 Mask handle correctly.
				return true;
			}
			
			public override Int32 RequestText(string text)
			{
				Int32 retVal = lookup.Text.IndexOf(text, foundStart);
				if (retVal != -1)
					foundEnd = retVal+1;
				return retVal;
			}
			
			public tlLookupMask(tagLookup aLookup) : base(aLookup)
			{
				
			}
		}
		
		
		internal class tagLookup
		{
			public List<tlLookupTag> TagList = new List<tlLookupTag>();
			public string Text;
			
			internal static tlLookupTag CreateLookupTag(tagLookup lookup, string param, bool isMask)
			{
				if (isMask)
					return new tlLookupMask(lookup);
				return new tlLookupText(lookup, param);
			}
			
			public tagLookup(string aText, string aMask)
			{
				Text = aText;
				string m = aMask;
				
				Int32 idx = m.IndexOf('*');
				while (idx != -1)
				{
					if (idx > 1)
						TagList.Add(CreateLookupTag(this, m.Substring(0, idx), false));
					TagList.Add(CreateLookupTag(this, "", true));
					m = m.Remove(0, idx+1);
					idx = m.IndexOf('*');
				}
				if (m != "") TagList.Add(CreateLookupTag(this, m, false));
			}
			
			public bool Found()
			{
				
				Int32 idx = -1;
				
				foreach (tlLookupTag tag in TagList)
				{
					if (tag.Found(idx))
						idx = (tag.foundEnd);
					else return false;
				}
				
				return (idx == this.Text.Length);  //13-06-07 Mask handle correctly.
			}
		}
		
		/// <summary>
		/// Return whether the text match a mask.
		/// </summary>
		public static bool MatchMask(string aText, string aMask)
		{
			tagLookup Lookup = new tagLookup(aText, aMask);
			return Lookup.Found();
		}
		
		public static bool MatchMask(string aText, string aMask, bool ignoreCase)
		{
			if (ignoreCase)
				return MatchMask(aText.ToLower(), aMask.ToLower());
			else
				return MatchMask(aText, aMask);
		}
		#endregion						
		
		#region System
		/// <summary>
		/// Run (execute) a file.
		/// </summary>
		public static void Run(string fileName, string param)
		{
			ShellExecute(IntPtr.Zero, SH_OPENFILE, fileName, param, "",
			             (Int32)ShellExecuteShowCmds.ShowNormal);
		}
		
		public static void RunShellCmd(string command, string filename)
		{
			if ((command != "") && (command != "Open with..."))
			ShellExecute(IntPtr.Zero, command, filename, "", "",
			             (Int32)ShellExecuteShowCmds.ShowNormal);
			else
				ShellExecute(IntPtr.Zero, "Open", "rundll32.exe", 
				             "shell32.dll,OpenAs_RunDLL " + filename, "",
			            	 (Int32)ShellExecuteShowCmds.ShowNormal);
		}
		
		/// <summary>
		/// Run a file and freeze till it's completed.
		/// </summary>
		public static void RunAndWait(string fileName, string param)
		{
			ProcessStartInfo processStartInfo =
				new ProcessStartInfo(fileName.Trim(), param.Trim());
			Process process = new Process();
			process.StartInfo = processStartInfo;
			bool processStarted = process.Start();
			if (processStarted)
			{
				
				process.WaitForExit();
			}			
		}
	
		/// <summary>
		/// Run a dos executable and capture it's output.
		/// </summary>
		public static Int32 RunDos(string fileName, string param, out string output)
		{
			//Ref: http://www.codeproject.com/csharp/ProcessStartDemo.asp
			Int32 exitCode = -1;
			output = "";
			
			StreamReader outputReader = null;
			StreamReader errorReader = null;			
			
			try
			{
				ProcessStartInfo processStartInfo =
					new ProcessStartInfo(fileName.Trim(), param.Trim());
				processStartInfo.ErrorDialog = false;
				processStartInfo.UseShellExecute = false;
				processStartInfo.RedirectStandardError = true;
				processStartInfo.RedirectStandardInput = true;
				processStartInfo.RedirectStandardOutput = true;
				
				Process process = new Process();
				process.StartInfo = processStartInfo;
				bool processStarted = process.Start();
				if (processStarted)
				{
					//Get the output stream
					outputReader = process.StandardOutput;
					errorReader = process.StandardError;
					process.WaitForExit();

					//Display the result
					output = outputReader.ReadToEnd();
					exitCode = process.ExitCode;
				}
				
			}
			catch 
			{
				return -1;
			}
			finally
			{
				if(outputReader != null)
				{
					outputReader.Close();
				}
				if(errorReader != null)
				{
					errorReader.Close();
				}				
			}														
			return exitCode;
			
		}
		
		
		
		/// <summary>
		/// Registers a file type via it's extension. If the file type is already registered, nothing is changed.		
		/// </summary>
		/// Based on Matthias's work. (http://www.codeproject.com/dotnet/System_File_Association.asp)
		/// <param name="extension">The extension to register</param>
		/// <param name="progId">A unique identifier for the program to work with the file type</param>
		/// <param name="description">A brief description of the file type</param>
		/// <param name="executeable">Where to find the executeable.</param>
		/// <param name="iconFile">Location of the icon.</param>
		/// <param name="iconIdx">Selects the icon within <paramref name="iconFile"/></param>
		public static void AssociatePrograms(string extension, string progId, string description, string executeable, string iconFile, int iconIdx)
		{
			try
			{
				if (extension.Length != 0)
				{
					if (extension[0] != '.')
					{
						extension = "."+extension;
					}

					// register the extension, if necessary
					using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension))
					{
						if (key == null)
						{
							using (RegistryKey extKey = Registry.ClassesRoot.CreateSubKey(extension))
							{
								extKey.SetValue(string.Empty, progId);
							}
						}
					}

					// register the progId, if necessary
					using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(progId))
					{
						if (key == null)
						{
							using (RegistryKey progIdKey = Registry.ClassesRoot.CreateSubKey(progId))
							{
								progIdKey.SetValue(string.Empty, description);
								progIdKey.SetValue("DefaultIcon", String.Format("\"{0}\",{1}", iconFile, iconIdx));

								using (RegistryKey command = progIdKey.CreateSubKey("shell\\open\\command"))
								{
									command.SetValue(string.Empty, String.Format("\"{0}\" \"%1\"", executeable));
								}
							}
						}
					}
				}
			}
			catch  //(Exception ex)
			{
				// TODO: implement proper exception handling.
			}
		}

		#endregion
		
		#region Archive
		
		/// <summary>
		/// Return if the specify file is an archive.
		/// </summary>
		public static bool isArchive(string fileName)
		{
			return Cakdir3.SupportedArchives().IndexOf(ExtractFileExt(fileName)) != -1;
		}
		
		/// <summary>
		/// Convert an archive to another type.
		/// Process may fail if the archive is encrypted.
		/// </summary>
		public static bool ArchiveConvert(string srcArchive, string destArchive)
		{
			string tempPath = NewTempPath("CAKE3");	
			
			Cakdir3 c3s = new Cakdir3(srcArchive);
			c3s.ExtractOptions.allowFolder = true;
			c3s.ExtractOptions.extractFolder = tempPath;
			if (!c3s.Extract())
				return false;
			
			Cakdir3 c3d = new Cakdir3(destArchive);
			c3d.AddOptions.addFile = new string[1] { tempPath + "*" };
			c3d.AddOptions.addFolder = AddOptions.folderMode.relative;
			c3d.AddOptions.baseFolder = tempPath;
			if (!c3d.Add())
				return false;
			
			
			
			return true;
		}					
		#endregion
		/// <summary>
		/// About message.
		/// </summary>
		public static void ShowAboutCAKE()
		{
			AboutCAKE dlg = new AboutCAKE();
			dlg.ShowDialog();
		}						
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder
Hong Kong Hong Kong

Comments and Discussions