Makale Özeti

Bundan bir önce yayınlanan makalemde yine C#.Net kullanarak Microsoft Word üzerinde bir kolaylık sağlamıştık. Şimdi ise kendi Windows Explorer’ımızı yazacağız.

Makale

C#.Net ile Windows Explorer

 

Bundan bir önce yayınlanan makalemde yine C#.Net kullanarak Microsoft Word üzerinde bir kolaylık sağlamıştık. Şimdi ise kendi Windows Explorer’ımızı yazacağız.

 

Bu uygulamamızda kullanacağımız namespaceler:

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.IO;

using System.Management;

using System.Globalization;

 

Ayrıca splitter, mainmenu, menuitem, treeview, listview, ve imagelist gibi kontroller de kullanacağız. Farklı ve çok yararlı bir makale olacağına inanıyorum.

 

Öncelikle aşağıdaki görüntüyü oluşturmanız gerekiyor.

 

 

My Computer’ın yazdığı kısımdaki resimleri image liste atarak çağırıyoruz. Bu tip resimleri Windows’un kendi sistem dosyalarından bulabileceğiniz gibi arama motorlarından da faydalanabilirsiniz.

 

Şimdi ise kodlarımıza gelelim. Kodlar uzun olduğundan dolayı iyi takip etmeniz ve anlayabilmeniz gerekmektedir. Açıkçası ben zor bir noktası olduğunu sanmıyorum. Zira her kodun açıklaması satır aralarında mutlaka yer alacaktır. Ancak her türlü durumda mail atarak benden yardım alabilirsiniz. Şimdi kod bölümünüze geçelim:

 

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.IO;

using System.Management;

using System.Globalization;

 

 

namespace My_Explorer

{

            public class Explorer : System.Windows.Forms.Form

            {

                        private System.Windows.Forms.Splitter splitter1;

                        private System.Windows.Forms.MainMenu mainMenu1;

                        private System.Windows.Forms.MenuItem menuItem1;

                        private System.Windows.Forms.MenuItem menuItem2;

                        private System.Windows.Forms.MenuItem menuItem3;

                        private System.Windows.Forms.MenuItem menuItem4;

                        private System.Windows.Forms.TreeView tvFolders;

                        private System.Windows.Forms.ListView lvFiles;

                        private System.Windows.Forms.ImageList m_imageListTreeView;

                        private System.ComponentModel.IContainer components;

 

                        public Explorer()

                        {

                                   InitializeComponent();

            PopulateDriveList();

                        }

 

                        protected override void Dispose( bool disposing )

                        {

                                   if( disposing )

                                   {

                                               if (components != null)

                                               {

                                                           components.Dispose();

                                               }

                                   }

                                   base.Dispose( disposing );

                        }

 

 

                        [STAThread]

                        static void Main()

                        {

                                   Application.Run(new Explorer());

                        }

 

                        //Bu prosedürde treeviewin içeriğini listeliyoruz

                        private void PopulateDriveList()

                        {

                                   TreeNode nodeTreeNode;

                                   int imageIndex = 0;

                                   int selectIndex = 0;

 

                                   const int Removable = 2;

                                   const int LocalDisk = 3;

                                   const int Network = 4;

                                   const int CD = 5;

                                   this.Cursor = Cursors.WaitCursor;

                                   // TreeView’i temizliyoruz

                                   tvFolders.Nodes.Clear();

                                   nodeTreeNode = new TreeNode("My Computer",0,0);

                                   tvFolders.Nodes.Add(nodeTreeNode);

 

                                   //Nod koleksiyonunu tanımlıyoruz

                                   TreeNodeCollection nodeCollection = nodeTreeNode.Nodes;

 

                                   //Ve şimdi sürücü listemizi oluşturuyoruz

                                   ManagementObjectCollection queryCollection = getDrives();

                                   foreach ( ManagementObject mo in queryCollection)

                                   {

                                  

                                                switch (int.Parse( mo["DriveType"].ToString()))

                                               {

                                                           case Removable:                                  //removable drives

                                                                       imageIndex = 5;

                                                                       selectIndex = 5;

                                                                       break;

                                                           case LocalDisk:                         //Local drives

                                                                       imageIndex = 6;

                                                                       selectIndex = 6;

                                                                       break;

                                                           case CD:                                              //CD rom drives

                                                                       imageIndex = 7;

                                                                       selectIndex = 7;

                                                                       break;

                                                           case Network:                          //Network drives

                                                                       imageIndex = 8;

                                                                       selectIndex = 8;

                                                                       break;

                                                           default:                                               //defalut to folder

                                                                       imageIndex = 2;

                                                                       selectIndex = 3;

                                                                       break;

                                               }

                                               //Yeni bir sürücü nodu oluşturuyoruz

                                               nodeTreeNode = new TreeNode(mo["Name"].ToString() + "\\" ,imageIndex,selectIndex);

 

                                               //Yeni bir nod tanımlıyoruz

                                               nodeCollection.Add(nodeTreeNode);

                }

            //Nodlarda çeşitli başlıklar simgelenecektir
//Buna en güzel örnek program files.
//Örnegin program files tiklandiktan sonra soldaki listview’e
//Program filesin tüm icerigi gelecektir

                                   InitListView();

 

                                   this.Cursor = Cursors.Default;

           }

 

                        private void tvFolders_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)

                        {

                                   //Hangi dosya secildiyse

//O dosyanin icerigini gerekli yere listeliyoruz

                                   this.Cursor = Cursors.WaitCursor;

 

                                   //Seçilen dosya yada sürücüyü listeliyoruz

                                   TreeNode nodeCurrent = e.Node;

 

                                   //Tüm alt dosyaları temizliyoruz

                                   nodeCurrent.Nodes.Clear();

 

                                   if (nodeCurrent.SelectedImageIndex == 0)

                                   {

                                               //Bilgisayarım secildikten sonra

//Daha önce yazdigimiz prosedürün calismasini saglayip

//Sürücü ve dosyaların gelmesini saglıyoruz

                                               PopulateDriveList();

                                   }

                                   else

                                   {

                                               //Burada ise alt dosyaların görüntülenmesini saglıyoruz

                                               PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);

                                   }

                                   this.Cursor = Cursors.Default;

                        }

                       

                        protected void InitListView()

                        {

                                   //Listviewin icerigini temizliyoruz

                                   lvFiles.Clear();             

                                   //Listview’in kolon baslıklarını tanımlıyoruz

                                   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);

                        }

 

                        protected void PopulateDirectory(TreeNode nodeCurrent, TreeNodeCollection nodeCurrentCollection)

                        {

                                   TreeNode nodeDir;

                                   int imageIndex = 2;      

                                   int selectIndex = 3;      

 

            if (nodeCurrent.SelectedImageIndex != 0)

                                   {

                                               //treeviewlere klasörler yerlestiriliyor

                                               try

                                               {

                                                           //dosya yolları kontrol ediliyor

                                                           if(Directory.Exists(getFullPath(nodeCurrent.FullPath)) == false)

                                                           {

                                                                       MessageBox.Show("Directory or path " + nodeCurrent.ToString() + " does not exist.");

                                                           }

                                                           else

                                                           {

                                                                       //dosyalar yerlestiriliyor

                                                                       PopulateFiles(nodeCurrent);

 

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

                                                                       string stringFullPath = "";

                                                                       string stringPathName = "";

 

                                                                       //yolların adresleri atanıyor

                                                                       foreach (string stringDir in stringDirectories)

                                                                       {

                                                                                  stringFullPath = stringDir;

                                                                                  stringPathName = GetPathName(stringFullPath);

                                                                                 

                                                                                  //adresler icin yeni nodlar olusturuluyor

                                                                                  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);

                                               }

                                   }

                        }

 

                        protected string GetPathName(string stringPath)

                        {

                                   //klasör isimleri getiriliyor

                                   string[] stringSplit = stringPath.Split('\\');

                                   int _maxIndex = stringSplit.Length;

                                   return stringSplit[_maxIndex-1];

                        }

 

                        protected void PopulateFiles(TreeNode nodeCurrent)

                        {

                                   //dosyalar treeviewe baglaniyor

                                   string[] lvData =  new string[4];

                                  

                                   //liste temizleniyor

                                   InitListView();

 

                                   if (nodeCurrent.SelectedImageIndex != 0)

                                   {

                                               //dosya yollari tekrar kontrol ediliyor

                                               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;

 

                                                                       //tüm dosyalar baglanıyor

                                                                       foreach (string stringFile in stringFiles)

                                                                       {

                                                                                  stringFileName = stringFile;

                                                                                  FileInfo objFileSize = new FileInfo(stringFileName);

                                                                                  lFileSize = objFileSize.Length;

                                                                                  dtCreateDate = objFileSize.CreationTime;

                                                                                  dtModifyDate = objFileSize.LastWriteTime;

 

                                                                                  //listviewedeki tüm veriler olusturuluyor

                                                                                  lvData[0] = GetPathName(stringFileName);

                                                                                  lvData[1] = formatSize(lFileSize);

                                                                                 

                                                                                  //dosyalar son kaydedilme yerlerine göre olusturuluyor

                                                                                  if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(dtCreateDate) == false)

                                                                                  {

                                                                                              //dosyaları son haliyle olusturuluyor

                                                                                              lvData[2] = formatDate(dtCreateDate.AddHours(1));

                                                                                  }

                                                                                  else

                                                                                  {

                                                                                              // dosyalar son kaydedilme yerlerine göre olusturuluyor

                                                                                              lvData[2] = formatDate(dtCreateDate);

                                                                                  }

 

                                                                                  //dosyaların en son ne zaman olusturulduguna bakılıyor

                                                                                  if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(dtModifyDate) == false)

                                                                                   {

                                                                                              dosyalar son kaydedilme yerlerine göre olusturuluyor

                                                                                              lvData[3] = formatDate(dtModifyDate.AddHours(1));

                                                                                  }

                                                                                  else                                                                            

                                                                                  {

                                                                                              // dosyalar son kaydedilme yerlerine göre olusturuluyor

                                                                                              lvData[3] = formatDate(dtModifyDate);

                                                                                  }

                                                                                  //gercek dosya yolları olusturuluyor

                                                                                  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);

                                                           }

                                               }

                                   }

                        }

 

                        protected string getFullPath(string stringPath)

                        {

                                   //tüm dosya yolları belirleniyor

                                   string stringParse = "";

                                   //bilgisayarımın yolu siliniyor

                                   stringParse = stringPath.Replace("My Computer\\", "");

 

                                   return stringParse;

                        }

                       

                        protected ManagementObjectCollection getDrives()

                        {

                                   //tüm sürücüler belirleniyor

                                   ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");

                                   ManagementObjectCollection queryCollection = query.Get();

                                   return queryCollection;

                        }

 

                        protected string formatDate(DateTime dtDate)

                        {

                                   //kucuk formatta tarih belirleniyor

                                   string stringDate = "";

 

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

 

                                   return stringDate;

                        }

 

                        protected string formatSize(Int64 lSize)

                        {

                                   //format numarasi 0 kb olarak belirleniyor

                                   string stringSize = "";

                                   NumberFormatInfo myNfi = new NumberFormatInfo();

 

                                   Int64 lKBSize = 0;

 

                                   if (lSize < 1024 )

                                   {

                                               if (lSize == 0)

                                               {

                                                           //0 byte

                                                           stringSize = "0";

                                               }

                                               else

                                               {

                                                           //1 kb’den daha az

                                                           stringSize = "1";

                                               }

                                   }

                                   else

                                   {

                                               // KB’ye cevriliyor

                                               lKBSize = lSize / 1024;

                                               //format numaralari default ayarlarina ceviriliyor

                                               stringSize = lKBSize.ToString("n",myNfi);

                                               //decimallar siliniyor

                                               stringSize = stringSize.Replace(".00", "");

                                   }

                                   return stringSize + " KB";

 

                        }

 

                        private void menuItem2_Click(object sender, System.EventArgs e)

                        {

                                   //uygulamadan cikiliyor

                                   this.Close();

                        }

            }

}

 

 

Tüm kodlarımız açıklamalarıyla birlikte bu şekilde oluşturuluyor. Eğer iyi takip ettiyseniz çalıştırdıktan sonra oluşması gereken görüntü şu şekilde olmalı:

 

 

İşe yarar, c#.net konusunda pratik dünyamızı genişleten ve geliştiren bir makale olduğuna inanıyorum. Farklı makalelerde tekrar görüşmek üzere.

 

Yağız GÖNÜLER

yagizgonuler@gmail.com