블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
반응형

Category

Recent Post

Recent Comment

Archive

'.Net Project/C# Project'에 해당되는 글 6

  1. 2009.09.14 C# 프로그램 모음1
  2. 2009.09.14 05장 급여처리
  3. 2009.09.14 04장 주소록
  4. 2009.09.14 03장 My ExPlorer 만들기
2009. 9. 14. 22:04 .Net Project/C# Project
반응형
반응형

'.Net Project > C# Project' 카테고리의 다른 글

05장 급여처리  (0) 2009.09.14
04장 주소록  (0) 2009.09.14
03장 My ExPlorer 만들기  (0) 2009.09.14
02장 계산기 만들기  (0) 2009.09.14
01장 메모장 만들어 보기  (0) 2009.09.14
posted by Magic_kit
2009. 9. 14. 21:58 .Net Project/C# Project
반응형

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 급여처리프로그램
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        List<Money> money = new List<Money>(); // DB
        private bool IsOnlyNum(int 사번) {
            bool result = false;
            for (int i = 0; i < money.Count; i++) {
                if (money[i].사번 == 사번) {
                    result = true;
                }
            }
            return result;
        }

        private void btn입력_Click(object sender, EventArgs e) {
            Money m = new Money();
            if (!Char.IsDigit(txt사번.Text, 0))
            {
                MessageBox.Show("사번은 정수라니까???"); return;
            }
            // 중복 제거
            if ( ! IsOnlyNum(Convert.ToInt32(txt사번.Text))) {
                m.사번 = Convert.ToInt32(txt사번.Text); 
            }
            else {
                MessageBox.Show("이미 있는 사원입니다.");
                txt사번.Focus(); txt사번.Select();
                return;
            }

            m.급 = Convert.ToInt32(cbo급.Items[
                cbo급.SelectedIndex].ToString().Substring(0, 1));
            m.호 = Convert.ToInt32(com호.Items[
                com호.SelectedIndex].ToString().Substring(0, 1));
            m.수당 = Convert.ToInt32(txt수당.Text);

            money.Add(m); // 하나씩 추가

            ClearText();
            this.txt사번.Focus();
        }

        private void ClearText()
        {
            txt사번.Text = txt수당.Text = "";
            cbo급.SelectedIndex = 0;
            com호.SelectedIndex = 0;
        }

        private void cmd출력_Click(object sender, EventArgs e)
        {
            // Process
            ProcessData();

            // Sort
            IEnumerable<Money> q = (from m in money
                                   orderby m.사번
                                   select m).ToList();

            // 입력 데이터 출력
            this.dgvPrint.DataSource = q;
        }

        private void ProcessData()
        {
            for (int i = 0; i < money.Count; i++)
            {
                // 지급액 : 급 호봉 계산표
                money[i].지급액 =
                    Calc지급액(money[i].급, money[i].호) + money[i].수당;
               
                // 세금
                money[i].세금 = Calc세금(money[i].지급액); 
                
                // 차인지급액

                money[i].차인지급액 = money[i].지급액 - money[i].세금;
            }
        }

        private int Calc세금(int 지급액)
        {
            int tax = 0;

            if (지급액 < 70000)
            {
                tax = (지급액 * 0) - 0;
            }
            else if (지급액 < 80000)
            {
                tax = Convert.ToInt32(지급액 * 0.005) - 300;
            }
            else if (지급액 < 90000)
            {
                tax = Convert.ToInt32(지급액 * 0.007) - 500;
            }
            else
            {
                tax = Convert.ToInt32(지급액 * 0.012) - 1000;
            }

            return tax;
        }
        private int Calc지급액(int 급, int 호)
        {
            int result = 0;
            if (급 == 1)
            {
                switch (호)
                {
                    case 1: result = 95000; break;
                    case 2: result = 92000; break;
                    case 3: result = 89000; break;
                    case 4: result = 86000; break;
                    case 5: result = 83000; break;
                    default:
                        break;
                }
            }
            else
            {
                switch (호)
                {
                    case 1: result = 80000; break;
                    case 2: result = 75000; break;
                    case 3: result = 70000; break;
                    case 4: result = 65000; break;
                    case 5: result = 60000; break;
                    default:
                        break;
                }
            }
            return result;
        }
    }
}







 

반응형

'.Net Project > C# Project' 카테고리의 다른 글

C# 프로그램 모음  (1) 2009.09.14
04장 주소록  (0) 2009.09.14
03장 My ExPlorer 만들기  (0) 2009.09.14
02장 계산기 만들기  (0) 2009.09.14
01장 메모장 만들어 보기  (0) 2009.09.14
posted by Magic_kit
2009. 9. 14. 19:21 .Net Project/C# Project
반응형



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace 주소록
{
    public partial class MainForm : Form
    {
        private List<Address> addr;
        private string dir = System.IO.Path.Combine(Application.StartupPath, "MyAddress.txt");

        public MainForm()
        {
            InitializeComponent();
            addr = new List<Address>();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (File.Exists(dir))
            {
                LoadData();      
            }
            this.sslCount.Text = "등록수 : " + addr.Count.ToString();
            if (addr.Count > 0)
            {
                ShowRecord(0); // 첫번째 데이터를 표시
                btnAdd.Text = "추가";
            }
        }

        private void LoadData()
        {
            StreamReader sr = new StreamReader(dir, Encoding.Default);
            while (sr.Peek() >= 0) // -1 : 더 이상 읽을 문자가 없을때
            {
                string[] arr = sr.ReadLine().Trim().Split(',');

                if (arr[0] != "" && arr[0] != null) {
                    Address a = new Address();
                    a.Num = Convert.ToInt32(arr[0]); // 번호 : 인덱스+1
                    a.Name = arr[1];
                    a.Mobile = arr[2];
                    a.Email = arr[3];

                    addr.Add(a); 
                }
            }
            sr.Close(); //
            sr.Dispose(); //
            DisplayData();
        }

        private void btnAdd_Click(object sender, EventArgs e) {
            if (btnAdd.Text == "입력") {
                Address a = new Address();
                a.Num = addr.Count + 1; //
                a.Name = txtName.Text.Trim();
                a.Mobile = txtMobile.Text.Trim();
                a.Email = txtEmail.Text.Trim();
                addr.Add(a);
                DisplayData(); // 출력
            }
            else {
                btnAdd.Text = "입력";
            }
            ClearTextBox();
        }

        private void ClearTextBox()
        {
            txtName.Text = txtMobile.Text = txtEmail.Text = String.Empty;
        }

        private void DisplayData()
        {
            var q = (from a in addr select a).ToList();
            this.dgvAddress.DataSource = q;
        }
        // 검색전용
        private void DisplayData(string query)
        {
            var q = (from a in addr
                     where
                        a.Name == query ||
                        a.Mobile == query ||
                        a.Email == query
                     select a).ToList();
            this.dgvAddress.DataSource = q;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (addr.Count > 0)
            {
                SaveData();
            }
        }

        private void SaveData()
        {
            // 레코드는 엔터구분, 필드는 콤마구분으로 저장
            StringBuilder sb = new StringBuilder();
            int index = 0;
            foreach (Address a in addr)
            {
                sb.AppendLine(String.Format("{0},{1},{2},{3}"
                    , ++index, a.Name, a.Mobile, a.Email));
            }
            StreamWriter sw = new StreamWriter(dir, false, Encoding.Default);
            sw.Write(sb.ToString());
            sw.Close();
            sw.Dispose(); //
            MessageBox.Show("저장되었습니다.");
        }

        private void miBackup_Click(object sender, EventArgs e)
        {
            string name = Path.GetFileNameWithoutExtension(dir);
            string ext = Path.GetExtension(dir).Replace(".", "");
 
            // MyAddress20100101.txt로 저장가능하도록
            string newDir =
                Path.Combine(Application.StartupPath,
                    String.Format("{0}{1}.{2}"
                        , name
                        , String.Format("{0}{1:0#}{2}"
                            , DateTime.Now.Year
                            , DateTime.Now.Month
                            , DateTime.Now.Day.ToString().PadLeft(2, '0')
                          )
                        , ext
                    )
                );

            if (File.Exists(dir))
            {               
                File.Copy(dir, newDir, true); // 원본을 복사해서 백업
            }
        }

        private void miExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private int currentIndex = -1;
        private void dgvAddress_CellClick(object sender,
            DataGridViewCellEventArgs e)
        {
            //currentIndex = e.RowIndex; // 현재 인덱스를 필드에 보관
            DataGridViewCell dgvc = dgvAddress.Rows[e.RowIndex].Cells[0];
            currentIndex = Convert.ToInt32(dgvc.Value.ToString()) - 1;
            if (currentIndex != -1)
            {
                ShowRecord(currentIndex);
            }
        }

        private void ShowRecord(int index)
        {
            // 현재 선택된 인덱스 + 1을 번호 출력
            this.txtNum.Text = (index + 1).ToString();
            this.txtName.Text = addr[index].Name;
            this.txtMobile.Text = addr[index].Mobile;
            this.txtEmail.Text = addr[index].Email;

            btnAdd.Text = "추가";
            txtGo.Text = txtNum.Text; // 현재 선택된 인덱스 값 출력
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            if (currentIndex != -1 && blnModified == true)
            {
                // 변경된 데이터로 addr 개체의 현재 인덱스 데이터 변경
                addr[currentIndex].Name = txtName.Text;
                addr[currentIndex].Mobile = txtMobile.Text;
                addr[currentIndex].Email = txtEmail.Text;
                MessageBox.Show("수정되었습니다.", "수정완료");
                DisplayData();
                blnModified = false; // 다시 초기화
            }
        }

        // 3개 텍스트박스에서 KeyPress 이벤트 발생시 호출
        private bool blnModified = false;
        private void txtModify_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (txtNum.Text != "") // 데이터가 로드된 상태에서만
            {
                blnModified = true; // 변경되었다...
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (txtNum.Text != "" && currentIndex != -1)
            {
                DialogResult dr =
                    MessageBox.Show("정말로 삭제하시겠습니까?", "삭제확인"
                        , MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr != DialogResult.No)
                {
                    // 메모리 상에서 현재 레코드 삭제
                    addr.RemoveAt(currentIndex);
                    DisplayData(); 
                }
            }
        }

        // 처음, 이전, 다음, 마지막 버튼에 대한 공통 이벤트
        private void btnMove_Click(object sender, EventArgs e) {
            Button btn = sender as Button;
            if (btn == btnFirst) {
                if (currentIndex > 0) {
                    currentIndex = 0; // 0번째 인덱스로 표시
                }
            }
            else if (btn == btnPrev) {
                if (currentIndex > 0) {
                    currentIndex--;
                }
            }
            else if (btn == btnNext) {
                if (currentIndex < addr.Count - 1) {
                    currentIndex++;
                }
            }
            else if (btn == btnLast) {
                if (currentIndex != -1) {
                    currentIndex = addr.Count - 1;
                }
            }
            ShowRecord(currentIndex); // 다시 데이터 표시
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (txtGo.Text != "" && Convert.ToInt32(txtGo.Text) > 0
                    && Convert.ToInt32(txtGo.Text) <= addr.Count)
            {
                ShowRecord(Convert.ToInt32(txtGo.Text) - 1);    
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            DisplayData(txtSearch.Text);
        }
    }
}


반응형

'.Net Project > C# Project' 카테고리의 다른 글

C# 프로그램 모음  (1) 2009.09.14
05장 급여처리  (0) 2009.09.14
03장 My ExPlorer 만들기  (0) 2009.09.14
02장 계산기 만들기  (0) 2009.09.14
01장 메모장 만들어 보기  (0) 2009.09.14
posted by Magic_kit
2009. 9. 14. 19:18 .Net Project/C# Project
반응형



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
{
 // Author: Paul Li
 // Create Date: 8/1/2002
 
 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()
  {
   //
   // Required for Windows Form Designer support
   //
   InitializeComponent();

   // Populate TreeView with Drive list
   PopulateDriveList();
  }

  /// <summary>
  /// Clean up any resources being used.
  /// </summary>
  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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Explorer));
            this.tvFolders = new System.Windows.Forms.TreeView();
            this.m_imageListTreeView = new System.Windows.Forms.ImageList(this.components);
            this.splitter1 = new System.Windows.Forms.Splitter();
            this.lvFiles = new System.Windows.Forms.ListView();
            this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.menuItem2 = new System.Windows.Forms.MenuItem();
            this.menuItem3 = new System.Windows.Forms.MenuItem();
            this.menuItem4 = new System.Windows.Forms.MenuItem();
            this.SuspendLayout();
            //
            // tvFolders
            //
            this.tvFolders.Dock = System.Windows.Forms.DockStyle.Left;
            this.tvFolders.ImageIndex = 0;
            this.tvFolders.ImageList = this.m_imageListTreeView;
            this.tvFolders.Location = new System.Drawing.Point(0, 0);
            this.tvFolders.Name = "tvFolders";
            this.tvFolders.SelectedImageIndex = 0;
            this.tvFolders.Size = new System.Drawing.Size(202, 357);
            this.tvFolders.TabIndex = 2;
            this.tvFolders.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvFolders_AfterSelect);
            //
            // m_imageListTreeView
            //
            this.m_imageListTreeView.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("m_imageListTreeView.ImageStream")));
            this.m_imageListTreeView.TransparentColor = System.Drawing.Color.Transparent;
            this.m_imageListTreeView.Images.SetKeyName(0, "");
            this.m_imageListTreeView.Images.SetKeyName(1, "");
            this.m_imageListTreeView.Images.SetKeyName(2, "");
            this.m_imageListTreeView.Images.SetKeyName(3, "");
            this.m_imageListTreeView.Images.SetKeyName(4, "");
            this.m_imageListTreeView.Images.SetKeyName(5, "");
            this.m_imageListTreeView.Images.SetKeyName(6, "");
            this.m_imageListTreeView.Images.SetKeyName(7, "");
            this.m_imageListTreeView.Images.SetKeyName(8, "");
            //
            // splitter1
            //
            this.splitter1.Location = new System.Drawing.Point(202, 0);
            this.splitter1.Name = "splitter1";
            this.splitter1.Size = new System.Drawing.Size(3, 357);
            this.splitter1.TabIndex = 3;
            this.splitter1.TabStop = false;
            //
            // lvFiles
            //
            this.lvFiles.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lvFiles.Location = new System.Drawing.Point(205, 0);
            this.lvFiles.Name = "lvFiles";
            this.lvFiles.Size = new System.Drawing.Size(395, 357);
            this.lvFiles.TabIndex = 4;
            this.lvFiles.UseCompatibleStateImageBehavior = false;
            this.lvFiles.View = System.Windows.Forms.View.Details;
            //
            // mainMenu1
            //
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem1,
            this.menuItem3});
            //
            // menuItem1
            //
            this.menuItem1.Index = 0;
            this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem2});
            this.menuItem1.Text = "&File";
            //
            // menuItem2
            //
            this.menuItem2.Index = 0;
            this.menuItem2.Text = "&Close";
            this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
            //
            // menuItem3
            //
            this.menuItem3.Index = 1;
            this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem4});
            this.menuItem3.Text = "&Help";
            //
            // menuItem4
            //
            this.menuItem4.Index = 0;
            this.menuItem4.Text = "&About";
            //
            // Explorer
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(600, 357);
            this.Controls.Add(this.lvFiles);
            this.Controls.Add(this.splitter1);
            this.Controls.Add(this.tvFolders);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mainMenu1;
            this.Name = "Explorer";
            this.Text = "My Window Explorer";
            this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Explorer());
  }

  //This procedure populate the TreeView with the Drive list
  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;
   //const int RAMDrive = 6;

   this.Cursor = Cursors.WaitCursor;
   //clear TreeView
   tvFolders.Nodes.Clear();
   nodeTreeNode = new TreeNode("My Computer",0,0);
   tvFolders.Nodes.Add(nodeTreeNode);

   //set node collection
   TreeNodeCollection nodeCollection = nodeTreeNode.Nodes;

   //Get Drive list
   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;
    }
    //create new drive node
    nodeTreeNode = new TreeNode(mo["Name"].ToString() + "\\" ,imageIndex,selectIndex);

    //add new node
    nodeCollection.Add(nodeTreeNode);

   }


   //Init files ListView
   InitListView();

   this.Cursor = Cursors.Default;

  }

  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();
   }
   else
   {
    //populate sub-folders and folder files
    PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);
   }
   this.Cursor = Cursors.Default;
  }
  
  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);

  }

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

  protected string GetPathName(string stringPath)
  {
   //Get Name of folder
   string[] stringSplit = stringPath.Split('\\');
   int _maxIndex = stringSplit.Length;
   return stringSplit[_maxIndex-1];
  }

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

  protected string getFullPath(string stringPath)
  {
   //Get Full path
   string stringParse = "";
   //remove My Computer from path.
   stringParse = stringPath.Replace("My Computer\\", "");

   return stringParse;
  }
  
  protected ManagementObjectCollection getDrives()
  {
   //get drive collection
   ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
   ManagementObjectCollection queryCollection = query.Get();
   
   return queryCollection;
  }

  protected string formatDate(DateTime dtDate)
  {
   //Get date and time in short format
   string stringDate = "";

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

   return stringDate;
  }

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

  }

  private void menuItem2_Click(object sender, System.EventArgs e)
  {
   //quit application
   this.Close();
  }

 }
}



 

반응형

'.Net Project > C# Project' 카테고리의 다른 글

C# 프로그램 모음  (1) 2009.09.14
05장 급여처리  (0) 2009.09.14
04장 주소록  (0) 2009.09.14
02장 계산기 만들기  (0) 2009.09.14
01장 메모장 만들어 보기  (0) 2009.09.14
posted by Magic_kit
prev 1 2 next