Click here to Skip to main content
15,917,709 members
Home / Discussions / C#
   

C#

 
GeneralRe: Windows Service Syslog for UDP port 514 Pin
leppie10-Oct-08 6:18
leppie10-Oct-08 6:18 
GeneralRe: Windows Service Syslog for UDP port 514 Pin
Dimitris Tselios12-Oct-08 2:11
Dimitris Tselios12-Oct-08 2:11 
QuestionRe: Windows Service Syslog for UDP port 514 Pin
Mark Salsbery10-Oct-08 5:56
Mark Salsbery10-Oct-08 5:56 
QuestionShell Programming - Loading a file selected on list view component Pin
Gianpaolo Barci10-Oct-08 4:34
Gianpaolo Barci10-Oct-08 4:34 
AnswerRe: Shell Programming - Loading a file selected on list view component Pin
DaveyM6910-Oct-08 4:59
professionalDaveyM6910-Oct-08 4:59 
GeneralRe: Shell Programming - Loading a file selected on list view component [modified] Pin
Gianpaolo Barci10-Oct-08 5:07
Gianpaolo Barci10-Oct-08 5:07 
GeneralRe: Shell Programming - Loading a file selected on list view component Pin
Dave Kreskowiak10-Oct-08 5:22
mveDave Kreskowiak10-Oct-08 5:22 
AnswerRe: Shell Programming - MY CODE! Pin
Gianpaolo Barci10-Oct-08 6:12
Gianpaolo Barci10-Oct-08 6:12 
I´ll try to explain my code while my poor English let :P!! It´s a file manager (a TreeView and a ListView). The Tree View shows only FOLDERS and List View only FILES. A file manager similar to Windows explorer but with a RootNode set to an especific folder on an external HD. Only the Root node and subnodes are visible. This I´ve done but not working properlly... just working...
The problem I´m having is to load the program by double-clicking on the file in the ListView.

The code is shown down

using System;
using System.Drawing;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Management;
using System.Globalization;

namespace Painel_de_Controle_ETECH
{
	public class Workspace : System.Windows.Forms.Form
	{
		private System.Windows.Forms.TreeView tvFolders;
		private System.Windows.Forms.ImageList m_imageListTreeView;
		private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.Splitter splitter1;
		private System.Windows.Forms.ListView lvFiles;
		private System.Windows.Forms.TextBox textBox1;
		private System.Windows.Forms.Button button1;
		private System.ComponentModel.IContainer components;

		 

		public Workspace()
		{
			InitializeComponent();
			
			//Metodo para preencher a tvFolder
			PopulateDriveList();
		}

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Workspace));
			this.tvFolders = new System.Windows.Forms.TreeView();
			this.m_imageListTreeView = new System.Windows.Forms.ImageList(this.components);
			this.toolBar1 = new System.Windows.Forms.ToolBar();
			this.splitter1 = new System.Windows.Forms.Splitter();
			this.lvFiles = new System.Windows.Forms.ListView();
			this.textBox1 = new System.Windows.Forms.TextBox();
			this.button1 = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// tvFolders
			// 
			this.tvFolders.Dock = System.Windows.Forms.DockStyle.Left;
			this.tvFolders.ImageList = this.m_imageListTreeView;
			this.tvFolders.Location = new System.Drawing.Point(0, 32);
			this.tvFolders.Name = "tvFolders";
			this.tvFolders.Size = new System.Drawing.Size(168, 360);
			this.tvFolders.TabIndex = 2;
			this.tvFolders.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvFolders_AfterSelect);
			// 
			// m_imageListTreeView
			// 
			this.m_imageListTreeView.ImageSize = new System.Drawing.Size(16, 16);
			this.m_imageListTreeView.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("m_imageListTreeView.ImageStream")));
			this.m_imageListTreeView.TransparentColor = System.Drawing.Color.Transparent;
			// 
			// toolBar1
			// 
			this.toolBar1.AutoSize = false;
			this.toolBar1.DropDownArrows = true;
			this.toolBar1.Location = new System.Drawing.Point(0, 0);
			this.toolBar1.Name = "toolBar1";
			this.toolBar1.ShowToolTips = true;
			this.toolBar1.Size = new System.Drawing.Size(602, 32);
			this.toolBar1.TabIndex = 0;
			// 
			// splitter1
			// 
			this.splitter1.Location = new System.Drawing.Point(168, 32);
			this.splitter1.Name = "splitter1";
			this.splitter1.Size = new System.Drawing.Size(3, 360);
			this.splitter1.TabIndex = 5;
			this.splitter1.TabStop = false;
			// 
			// lvFiles
			// 
			this.lvFiles.Dock = System.Windows.Forms.DockStyle.Fill;
			this.lvFiles.Location = new System.Drawing.Point(171, 32);
			this.lvFiles.Name = "lvFiles";
			this.lvFiles.Size = new System.Drawing.Size(431, 360);
			this.lvFiles.TabIndex = 0;
			this.lvFiles.View = System.Windows.Forms.View.Details;
			// 
			// textBox1
			// 
			this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.textBox1.Location = new System.Drawing.Point(312, 8);
			this.textBox1.Name = "textBox1";
			this.textBox1.Size = new System.Drawing.Size(200, 20);
			this.textBox1.TabIndex = 6;
			this.textBox1.Text = "";
			// 
			// button1
			// 
			this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.button1.Location = new System.Drawing.Point(520, 8);
			this.button1.Name = "button1";
			this.button1.TabIndex = 7;
			this.button1.Text = "Refinar...";
			// 
			// Workspace
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(602, 392);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.textBox1);
			this.Controls.Add(this.lvFiles);
			this.Controls.Add(this.splitter1);
			this.Controls.Add(this.tvFolders);
			this.Controls.Add(this.toolBar1);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
			this.Name = "Workspace";
			this.ShowInTaskbar = false;
			this.Text = "Workspace";
			this.ResumeLayout(false);

		}
		#endregion

		


		#region Pupulate

		//Este método busca no banco de dados do sistema a lista de drives e exibe apenas os discos locais

		#region Criar DriveList
		private void PopulateDriveList()
		{
			//TreeNode nodeRoot;
			TreeNode nodeTreeNode;
			int imageIndex = 0;
			int selectIndex = 0;

			const int LocalDisk = 3;

			this.Cursor = Cursors.WaitCursor;
			//clear TreeView
			tvFolders.Nodes.Clear(); //limpa tvFolders.Nodes
			nodeTreeNode = new TreeNode("My Computer",0,0); //nodeTreeNode apontará para my computer
			/* Note que tvFolders ainda não exibe o nó! Isso ocorre para que ele não exiba o nó MyComputer */
			//Get Drive list
			ManagementObjectCollection queryCollection = getDrives(); //inicia-se a busca pelos drives
			foreach ( ManagementObject mo in queryCollection) //pra cada um deles encontrado
			{
			    //GET DRIVES TYPE (CDs, FLOPPIES...) but this will get only the Local drives...
				switch (int.Parse( mo["DriveType"].ToString())) //mo["DriveType"] receberá um parâmetro dos adaixo
				{
					case LocalDisk:			//Local drives.. O HD externo é estranhamente reconhecido como LocalDrive
						imageIndex = 6;
						selectIndex = 6;
						break;
					
					default:				//defalut to folder
						imageIndex = 2;
						selectIndex = 3;
						break;
				}
				//If the drive found is a Local Drive and it´s not C: then it will be shown (because the drive I want isn´t C:)
				if(int.Parse( mo["DriveType"].ToString()) == LocalDisk && mo["Name"].ToString() != "C:" )//you can set to show C: again if you wish to test it.
				{	
					//this will set to show (poorly) f:\Painel de Controle ETECH\Projetos ETECH as root
					nodeTreeNode = new TreeNode(mo["Name"].ToString() + "\\Painel de Controle ETECH\\Projetos ETECH",imageIndex,selectIndex); //nodeTreeNode receberá o nome do mesmo
					tvFolders.Nodes.Add(nodeTreeNode); //AGORA SIM o tvFolders exibirá o nó! (and then show the node on TreeView)
					
					//add nodeCollection
					TreeNodeCollection nodeCollection = nodeTreeNode.Nodes;
					nodeTreeNode.Expand(); //I´d like to show the root expanded (but it still appears collapsed...)
				}
			}


			//Init files ListView
			InitListView();   //lvFiles exibirá os arquivos.

			this.Cursor = Cursors.Default;

		}
		#endregion

		//Este método preenche a tvFolders com as pastas e subpastas
   		#region Preencher tvFolder
		private void tvFolders_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
		{
			//Populate folders and files when a folder is selected
			this.Cursor = Cursors.WaitCursor;

			//get current selected drive or folder
			TreeNode nodeCurrent = e.Node;

			//clear all sub-folders
			nodeCurrent.Nodes.Clear();

			if (nodeCurrent.SelectedImageIndex == 0) 
			{
				//Selected My Computer - repopulate drive list
				PopulateDriveList();
				//PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);
			}
			else 
			{
				//populate sub-folders and folder files
				PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);

			}
			this.Cursor = Cursors.Default;
		}
		#endregion

		//Este método apenas inicia lvFiles
		#region Iniciar lvFiles
		protected void InitListView()
		{
			//init ListView control
			lvFiles.Clear();		//clear control
			//create column header for ListView
			lvFiles.Columns.Add("Name",150,System.Windows.Forms.HorizontalAlignment.Left);
			lvFiles.Columns.Add("Size",75, System.Windows.Forms.HorizontalAlignment.Right);
			lvFiles.Columns.Add("Created", 140, System.Windows.Forms.HorizontalAlignment.Left);
			lvFiles.Columns.Add("Modified", 140, System.Windows.Forms.HorizontalAlignment.Left);

		}
		#endregion

		//Método que busca subdiretórios do nó para exibir no tvFolder
		#region Busacar Diretórios
		protected void PopulateDirectory(TreeNode nodeCurrent, TreeNodeCollection nodeCurrentCollection)
		{
			TreeNode nodeDir;
			int imageIndex = 2;		//unselected image index
			int selectIndex = 3;	//selected image index

			if (nodeCurrent.SelectedImageIndex != 0) 
			{
				//populate treeview with folders
				try
				{
					//check path
					if(Directory.Exists(getFullPath(nodeCurrent.FullPath)) == false)
					{
						MessageBox.Show("Directory or path " + nodeCurrent.ToString() + " does not exist.");
					}
					else
					{
						//populate files
						PopulateFiles(nodeCurrent);

						string[] stringDirectories = Directory.GetDirectories(getFullPath(nodeCurrent.FullPath));
						string stringFullPath = "";
						string stringPathName = "";

						//loop throught all directories
						foreach (string stringDir in stringDirectories)
						{
							stringFullPath = stringDir;
							stringPathName = GetPathName(stringFullPath);
							
							//create node for directories
							nodeDir = new TreeNode(stringPathName.ToString(),imageIndex,selectIndex);
							nodeCurrentCollection.Add(nodeDir);
						}
					}
				}
				catch (IOException e)
				{
					MessageBox.Show("Error: Drive not ready or directory does not exist.");
				}
				catch (UnauthorizedAccessException e)
				{
					MessageBox.Show("Error: Drive or directory access denided.");
				}
				catch (Exception e)
				{
					MessageBox.Show("Error: " + e);
				}
			}
		}
		#endregion

		//Este método pega o NOME dos diretórios e subdiretórios
		#region Nome dos Diretórios
		protected string GetPathName(string stringPath)
		{
			//Get Name of folder
			string[] stringSplit = stringPath.Split('\\');
			int _maxIndex = stringSplit.Length;
			return stringSplit[_maxIndex-1];
		}
		#endregion

		//Este método busca os arquivos do diretório para carrega-los no lvFiles
		#region Buscar Arquivos
		protected void PopulateFiles(TreeNode nodeCurrent)
		{
			//Populate listview with files
			string[] lvData =  new string[4];
			
			//clear list
			InitListView();

			if (nodeCurrent.SelectedImageIndex != 0) 
			{
				//check path
				if(Directory.Exists((string) getFullPath(nodeCurrent.FullPath)) == false)
				{
					MessageBox.Show("Directory or path " + nodeCurrent.ToString() + " does not exist.");
				}
				else
				{
					try
					{
						string[] stringFiles = Directory.GetFiles(getFullPath(nodeCurrent.FullPath));
						string stringFileName = "";
						DateTime dtCreateDate, dtModifyDate;
						Int64 lFileSize = 0;

						//loop throught all files
						foreach (string stringFile in stringFiles)
						{
							stringFileName = stringFile;
							FileInfo objFileSize = new FileInfo(stringFileName);
							lFileSize = objFileSize.Length;
							dtCreateDate = objFileSize.CreationTime; //GetCreationTime(stringFileName);
							dtModifyDate = objFileSize.LastWriteTime; //GetLastWriteTime(stringFileName);

							//create listview data
							lvData[0] = GetPathName(stringFileName);
							lvData[1] = formatSize(lFileSize);
							
							//check if file is in local current day light saving time
							if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(dtCreateDate) == false)
							{
								//not in day light saving time adjust time
								lvData[2] = formatDate(dtCreateDate.AddHours(1));
							}
							else
							{
								//is in day light saving time adjust time
								lvData[2] = formatDate(dtCreateDate);
							}

							//check if file is in local current day light saving time
							if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(dtModifyDate) == false)
							{
								//not in day light saving time adjust time
								lvData[3] = formatDate(dtModifyDate.AddHours(1));
							}
							else							
							{
								//not in day light saving time adjust time
								lvData[3] = formatDate(dtModifyDate);
							}


							//Create actual list item
							ListViewItem lvItem = new ListViewItem(lvData,0);
							lvFiles.Items.Add(lvItem);

							
						}
					}
					catch (IOException e)
					{
						MessageBox.Show("Error: Drive not ready or directory does not exist.");
					}
					catch (UnauthorizedAccessException e)
					{
						MessageBox.Show("Error: Drive or directory access denided.");
					}
					catch (Exception e)
					{
						MessageBox.Show("Error: " + e);
					}
				}
			}
		}
		#endregion

		//Este método pega o caminho dos diretórios e subdiretórios
		#region Pegar Caminho
		protected string getFullPath(string stringPath)
		{
			//Get Full path
			string stringParse = "";
			//remove My Computer from path.
			stringParse = stringPath.Replace("My Computer", "");

			return stringParse;
		}
		#endregion

		//Este método pega no banco de dados do sistema as informações sobre os dispositivos (drives)
		#region Buscar Lista de Drives
		protected ManagementObjectCollection getDrives()
		{
			//get drive collection
			ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
			ManagementObjectCollection queryCollection = query.Get();
			
			return queryCollection;
		}
		#endregion

        //Este método pega a data dos arquivos no sistema e é carregado por populateFiles
		#region Pegar Data
		protected string formatDate(DateTime dtDate)
		{
			//Get date and time in short format
			string stringDate = "";

			stringDate = dtDate.ToShortDateString().ToString() + " " + dtDate.ToShortTimeString().ToString();

			return stringDate;
		}
		#endregion

		//Este método converte os tamanhos dos aquivos para KB e é chamado por populateFiles
		#region Converter tamanho para KB
		protected string formatSize(Int64 lSize)
		{
			//Format number to KB
			string stringSize = "";
			NumberFormatInfo myNfi = new NumberFormatInfo();

			Int64 lKBSize = 0;

			if (lSize < 1024 ) 
			{
				if (lSize == 0) 
				{
					//zero byte
					stringSize = "0";
				}
				else 
				{
					//less than 1K but not zero byte
					stringSize = "1";
				}
			}
			else 
			{
				//convert to KB
				lKBSize = lSize / 1024;
				//format number with default format
				stringSize = lKBSize.ToString("n",myNfi);
				//remove decimal
				stringSize = stringSize.Replace(".00", "");
			}

			return stringSize + " KB";

		}
		#endregion

		#endregion

		#region Eventos de Shell

		#region Executar Arquivo
		private void executeFile() //This is the shell command I was trying to implement on mey code
		{
			ShellLib.ShellExecute shellExecute = new ShellLib.ShellExecute();
			shellExecute.Path = @"C:\Arquivos de programas\AutoCAD 2008\acad.exe";
			shellExecute.Execute();
		}
		#endregion

		//protected string getFilePath(string strFilePath)
	//	{
		
		//}

		#endregion
	}
}


Just ignore the comments in portuguese!! I translated some important lines to english!!!

If anyone could helpme I will be VERY pleased!!! very very very pleased!!! I will thank my whole life!!!!
GeneralRe: Shell Programming - MY CODE! Pin
Dave Kreskowiak10-Oct-08 6:49
mveDave Kreskowiak10-Oct-08 6:49 
GeneralRe: Shell Programming - MY CODE! Pin
Gianpaolo Barci10-Oct-08 7:00
Gianpaolo Barci10-Oct-08 7:00 
GeneralRe: Shell Programming - MY CODE! Pin
DaveyM6910-Oct-08 7:45
professionalDaveyM6910-Oct-08 7:45 
GeneralRe: Shell Programming - MY CODE! Pin
Gianpaolo Barci10-Oct-08 7:56
Gianpaolo Barci10-Oct-08 7:56 
GeneralRe: Shell Programming - MY CODE! Pin
DaveyM6910-Oct-08 8:25
professionalDaveyM6910-Oct-08 8:25 
GeneralRe: Shell Programming - MY CODE! Pin
Dave Kreskowiak10-Oct-08 8:27
mveDave Kreskowiak10-Oct-08 8:27 
GeneralRe: Shell Programming - MY CODE! Pin
Gianpaolo Barci10-Oct-08 9:34
Gianpaolo Barci10-Oct-08 9:34 
GeneralRe: Shell Programming - MY CODE! Pin
DaveyM6910-Oct-08 11:27
professionalDaveyM6910-Oct-08 11:27 
Questionmoving 2.0 to 3.0 and up Pin
netJP12L10-Oct-08 4:28
netJP12L10-Oct-08 4:28 
AnswerRe: moving 2.0 to 3.0 and up Pin
DaveyM6910-Oct-08 4:34
professionalDaveyM6910-Oct-08 4:34 
GeneralRe: moving 2.0 to 3.0 and up Pin
netJP12L10-Oct-08 4:40
netJP12L10-Oct-08 4:40 
GeneralRe: moving 2.0 to 3.0 and up Pin
DaveyM6910-Oct-08 4:52
professionalDaveyM6910-Oct-08 4:52 
GeneralRe: moving 2.0 to 3.0 and up Pin
Colin Angus Mackay10-Oct-08 12:51
Colin Angus Mackay10-Oct-08 12:51 
AnswerRe: moving 2.0 to 3.0 and up Pin
Pedram Behroozi10-Oct-08 4:41
Pedram Behroozi10-Oct-08 4:41 
QuestionHDD Serial Number Pin
sasan5610-Oct-08 3:59
sasan5610-Oct-08 3:59 
AnswerRe: HDD Serial Number Pin
Baconbutty10-Oct-08 4:20
Baconbutty10-Oct-08 4:20 
JokeRe: HDD Serial Number Pin
Thomas Stockwell10-Oct-08 4:26
professionalThomas Stockwell10-Oct-08 4:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.