Click here to Skip to main content
16,010,416 members
Home / Discussions / C#
   

C#

 
AnswerRe: from VB.NET to C# Pin
Tamimi - Code4-Jun-06 3:34
Tamimi - Code4-Jun-06 3:34 
AnswerRe: from VB.NET to C# Pin
Dave Doknjas4-Jun-06 12:30
Dave Doknjas4-Jun-06 12:30 
QuestionHow do you implement treeview.expand() method in C#? [modified] Pin
Tom Dane4-Jun-06 3:10
Tom Dane4-Jun-06 3:10 
AnswerRe: Append from an xml file to another xml file with C# Pin
Tamimi - Code4-Jun-06 3:04
Tamimi - Code4-Jun-06 3:04 
GeneralRe: Append from an xml file to another xml file with C# Pin
Yustme4-Jun-06 3:56
Yustme4-Jun-06 3:56 
GeneralRe: Append from an xml file to another xml file with C# Pin
Tamimi - Code4-Jun-06 4:00
Tamimi - Code4-Jun-06 4:00 
GeneralRe: Append from an xml file to another xml file with C# Pin
Yustme4-Jun-06 4:20
Yustme4-Jun-06 4:20 
GeneralNot sure if you understand my question??? Pin
Tom Dane4-Jun-06 16:08
Tom Dane4-Jun-06 16:08 
Not sure if you understand my question?
Appreciate the effort though...
I'm not doing anything with XML
This is just a simple treeview within a form
It's a continuation from some sample code from
a O'Riely book on c#
I have tried to put it in the expand method where
the code fills the directory with no success?

Don't know how to attach so
I will just paste what I have so far:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;

namespace FileCopier
{
///
/// Summary description for Form1.
///

public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TreeView tvwSource;
private System.Windows.Forms.TreeView tvwTargetDir;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.CheckBox chkOverwrite;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnCopy;
private System.Windows.Forms.Label lblStatus;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.TextBox txtTargetDir;
private System.Windows.Forms.Label lblSource;
private System.Windows.Forms.Label lblTarget;

private System.ComponentModel.Container components = null;


public class FileComparer : IComparer
{
public int Compare (object f1, object f2)
{
FileInfo file1 = (FileInfo) f1;
FileInfo file2 = (FileInfo) f2;
if (file1.Length > file2.Length)
{
return -1;
}
if (file1.Length < file2.Length)
{
return 1;
}
return 0;
}
}


public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//

// fill the source and target directory trees
FillDirectoryTree(tvwSource, true);
FillDirectoryTree(tvwTargetDir, false);

}

///
/// Fill the directory tree for either the Source or
/// Target TreeView.
///

private void FillDirectoryTree(
TreeView tvw, bool isSource)
{
// Populate tvwSource, the Source TreeView,
// with the contents of
// the local hard drive.
// First clear all the nodes.
tvw.Nodes.Clear();

// Get the logical drives and put them into the
// root nodes. Fill an array with all the
// logical drives on the machine.
string[] strDrives = Environment.GetLogicalDrives();

// Iterate through the drives, adding them to the tree.
// Use a try/catch block, so if a drive is not ready,
// e.g. an empty floppy or CD,
// it will not be added to the tree.
foreach (string rootDirectoryName in strDrives)
{
if (rootDirectoryName != @"C:\")
continue;
try
{

// Fill an array with all the first level
// subdirectories. If the drive is
// not ready, this will throw an exception.
DirectoryInfo dir =
new DirectoryInfo(rootDirectoryName);
dir.GetDirectories();

TreeNode ndRoot = new TreeNode(rootDirectoryName);

// Add a node for each root directory.
tvw.Nodes.Add(ndRoot);

// Add subdirectory nodes.
// If Treeview is the source,
// then also get the filenames.
if (isSource)
{
GetSubDirectoryNodes(
ndRoot, ndRoot.Text, true);
}
else
{
GetSubDirectoryNodes(
ndRoot, ndRoot.Text, false);
}
}
// Catch any errors such as
// Drive not ready.
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
} // close for FillSourceDirectoryTree

///
/// Gets all the subdirectories below the
/// passed in directory node.
/// Adds to the directory tree.
/// The parameters passed in at the parent node
/// for this subdirectory,
/// the full path name of this subdirectory,
/// and a Boolean to indicate
/// whether or not to get the files in the subdirectory.
///

private void GetSubDirectoryNodes(
TreeNode parentNode, string fullName, bool getFileNames)
{
DirectoryInfo dir = new DirectoryInfo(fullName);
DirectoryInfo[] dirSubs = dir.GetDirectories();

// Add a child node for each subdirectory.
foreach (DirectoryInfo dirSub in dirSubs)
{

// do not show hidden folders
if ( (dirSub.Attributes & FileAttributes.Hidden)
!= 0 )
{
continue;
}

///
/// Each directory contains the full path.
/// We need to split it on the backslashes,
/// and only use
/// the last node in the tree.
/// Need to double the backslash since it
/// is normally
/// an escape character
///

TreeNode subNode = new TreeNode(dirSub.Name);
parentNode.Nodes.Add(subNode);

// Call GetSubDirectoryNodes recursively.
GetSubDirectoryNodes(
subNode,dirSub.FullName,getFileNames);

}
if (getFileNames)
{
// Get any files for this node.
FileInfo[] files = dir.GetFiles();

// After placing the nodes,
// now place the files in that subdirectory.
foreach (FileInfo file in files)
{
TreeNode fileNode = new TreeNode(file.Name);
parentNode.Nodes.Add(fileNode);
}
}
}//close for private void GetSubDirectoryNodes

///
/// Clean up any resources being used.
///

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

#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.lblSource = new System.Windows.Forms.Label();
this.lblTarget = new System.Windows.Forms.Label();
this.btnClear = new System.Windows.Forms.Button();
this.btnCopy = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.chkOverwrite = new System.Windows.Forms.CheckBox();
this.txtTargetDir = new System.Windows.Forms.TextBox();
this.tvwSource = new System.Windows.Forms.TreeView();
this.tvwTargetDir = new System.Windows.Forms.TreeView();
this.lblStatus = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lblSource
//
this.lblSource.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblSource.Location = new System.Drawing.Point(100, 25);
this.lblSource.Name = "lblSource";
this.lblSource.Size = new System.Drawing.Size(150, 23);
this.lblSource.TabIndex = 0;
this.lblSource.Text = "Source Files";
this.lblSource.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblTarget
//
this.lblTarget.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblTarget.Location = new System.Drawing.Point(400, 25);
this.lblTarget.Name = "lblTarget";
this.lblTarget.Size = new System.Drawing.Size(175, 23);
this.lblTarget.TabIndex = 1;
this.lblTarget.Text = "Target Directory";
this.lblTarget.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(125, 450);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(100, 23);
this.btnClear.TabIndex = 2;
this.btnClear.Text = "Clear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnCopy
//
this.btnCopy.Location = new System.Drawing.Point(550, 450);
this.btnCopy.Name = "btnCopy";
this.btnCopy.TabIndex = 3;
this.btnCopy.Text = "Copy";
this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click);
//
// btnDelete
//
this.btnDelete.Location = new System.Drawing.Point(550, 500);
this.btnDelete.Name = "btnDelete";
this.btnDelete.TabIndex = 4;
this.btnDelete.Text = "Delete";
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(550, 550);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 5;
this.btnCancel.Text = "Cancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// chkOverwrite
//
this.chkOverwrite.Location = new System.Drawing.Point(425, 425);
this.chkOverwrite.Name = "chkOverwrite";
this.chkOverwrite.Size = new System.Drawing.Size(115, 24);
this.chkOverwrite.TabIndex = 6;
this.chkOverwrite.Text = "Overwrite if exists";
//
// txtTargetDir
//
this.txtTargetDir.Location = new System.Drawing.Point(350, 50);
this.txtTargetDir.Name = "txtTargetDir";
this.txtTargetDir.Size = new System.Drawing.Size(275, 20);
this.txtTargetDir.TabIndex = 7;
this.txtTargetDir.Text = "";
//
// tvwSource
//
this.tvwSource.CheckBoxes = true;
this.tvwSource.ImageIndex = -1;
this.tvwSource.Location = new System.Drawing.Point(50, 50);
this.tvwSource.Name = "tvwSource";
this.tvwSource.SelectedImageIndex = -1;
this.tvwSource.Size = new System.Drawing.Size(250, 375);
this.tvwSource.TabIndex = 8;
this.tvwSource.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.tvwSource_AfterCheck);
//
// tvwTargetDir
//
this.tvwTargetDir.ImageIndex = -1;
this.tvwTargetDir.Location = new System.Drawing.Point(350, 75);
this.tvwTargetDir.Name = "tvwTargetDir";
this.tvwTargetDir.SelectedImageIndex = -1;
this.tvwTargetDir.Size = new System.Drawing.Size(275, 350);
this.tvwTargetDir.TabIndex = 9;
this.tvwTargetDir.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvwTargetDir_AfterSelect);
//
// lblStatus
//
this.lblStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblStatus.Location = new System.Drawing.Point(50, 500);
this.lblStatus.Name = "lblStatus";
this.lblStatus.TabIndex = 0;
this.lblStatus.Text = "Status:";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(667, 591);
this.Controls.Add(this.tvwTargetDir);
this.Controls.Add(this.tvwSource);
this.Controls.Add(this.txtTargetDir);
this.Controls.Add(this.chkOverwrite);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnCopy);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.lblTarget);
this.Controls.Add(this.lblSource);
this.Controls.Add(this.lblStatus);
this.Name = "Form1";
this.Text = "File Copier";
this.ResumeLayout(false);

}
#endregion

///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

///
/// on cancel, exit
///

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

///
/// recursively set or clear check marks
///

private void SetCheck(TreeNode node, bool check)
{
// find all the child nodes from this node
foreach (TreeNode n in node.Nodes)
{
n.Checked = check; // check the node

// if this is a node in the tree, recurse
if (n.Nodes.Count != 0)
{
SetCheck(n,check);
}
}
}

///
/// Given a node and an array list
/// fill the list with the names of
/// all the checked files
///

// Fill the ArrayList with the full paths of
// all the files checked
private void GetCheckedFiles(TreeNode node,
ArrayList fileNames)
{
// if this is a leaf...
if (node.Nodes.Count == 0)
{
// if the node was checked...
if (node.Checked)
{
// get the full path and add it to the arrayList
string fullPath = GetParentString(node);
fileNames.Add(fullPath);
}
}
else // if this node is not a leaf
{
// if this node is not a leaf
foreach (TreeNode n in node.Nodes)
{
GetCheckedFiles(n,fileNames);
}
}
}

///
/// Given a node, return the
/// full path name
///

private string GetParentString(TreeNode node)
{
// if this is the root node (c:\) return the text
if(node.Parent == null)
{
return node.Text;
}
else
{
// recurse up and get the path then
// add this node and a slash
// if this node is the leaf, don't add the slash
return GetParentString(node.Parent) + node.Text +
(node.Nodes.Count == 0 ? "" : "\\");
}
}

///
/// shared by delete and copy
/// creates an ordered list of all
/// the selected files
///

private ArrayList GetFileList()
{
// create an unsorted array list of the full file names
ArrayList fileNames = new ArrayList();

// fill the fileNames ArrayList with the
// full path of each file to copy
foreach (TreeNode theNode in tvwSource.Nodes)
{
GetCheckedFiles(theNode, fileNames);
}

// Create a list to hold the FileInfo objects
ArrayList fileList = new ArrayList();

// for each of the file names we have in our unsorted list
// if the name corresponds to a file (and not a directory)
// add it to the file list
foreach (string fileName in fileNames)
{
// create a file with the name
FileInfo file = new FileInfo(fileName);

// see if it exists on the disk
// this fails if it was a directory
if (file.Exists)
{
// both the key and the value are the file
// would it be easier to have an empty value?
fileList.Add(file);
}
}

// Create an instance of the IComparer interface
IComparer comparer = (IComparer) new FileComparer();

// pass the comparer to the sort method so that the list
// is sorted by the compare method of comparer.
fileList.Sort(comparer);
return fileList;

}

/*
private void tvwSource_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
SetCheck(e.Node,e.Node.Checked);
Application.DoEvents();
}
*/
private void tvwSource_AfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
SetCheck(e.Node,e.Node.Checked);
}

///
/// Tell the root of each tree to uncheck
/// all the nodes below
///

private void btnClear_Click(object sender, System.EventArgs e)
{
// get the top most node for each drive
// and tell it to clear recursively
foreach (TreeNode node in tvwSource.Nodes)
{
SetCheck(node, false);
}
}

///
/// Create an ordered list of all
/// the selected files, copy to the
/// target directory
///

private void btnCopy_Click(object sender, System.EventArgs e)
{
// get the list
ArrayList fileList = GetFileList();

// copy the files
foreach (FileInfo file in fileList)
{
try
{
// update the label to show progress
lblStatus.Text = "Copying " + txtTargetDir.Text +
"\\" + file.Name + "...";
Application.DoEvents();

// copy the file to its destination location
file.CopyTo(txtTargetDir.Text + "\\" +
file.Name,chkOverwrite.Checked);
}

catch (Exception ex)
{
// you may want to do more than
// just show the message
MessageBox.Show(ex.Message);
}
}
lblStatus.Text = "Done.";
FillDirectoryTree(tvwSource, true);
FillDirectoryTree(tvwTargetDir, false);
Application.DoEvents();

}


///
/// check that the user does want to delete
/// Make a list and delete each in turn
///

private void btnDelete_Click(object sender, System.EventArgs e)
{
// ask them if they are sure
System.Windows.Forms.DialogResult result =
MessageBox.Show(
"Are you quite sure?", // msg
"Delete Files", // caption
MessageBoxButtons.OKCancel, // buttons
MessageBoxIcon.Exclamation, // icons
MessageBoxDefaultButton.Button2); // default button

// if they are sure...
if (result == System.Windows.Forms.DialogResult.OK)
{
// iterate through the list and delete them.
// get the list of selected files
ArrayList fileNames = GetFileList();

foreach (FileInfo file in fileNames)
{
try
{
// update the label to show progress
lblStatus.Text = "Deleting " +
txtTargetDir.Text + "\\" +
file.Name + "...";
Application.DoEvents();

// Danger Will Robinson!
file.Delete();
}

catch (Exception ex)
{
// you may want to do more than
// just show the message
MessageBox.Show(ex.Message);
}
}
lblStatus.Text = "Done.";
FillDirectoryTree(tvwSource, true);
FillDirectoryTree(tvwTargetDir, false);
Application.DoEvents();
}

}

///
/// Get the full path of the chosen directory
/// copy it to txtTargetDir
///

private void tvwTargetDir_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
// get the full path for the selected directory
string theFullPath = GetParentString(e.Node);

// if it is not a leaf, it will end with a back slash
// remove the backslash
if (theFullPath.EndsWith("\\"))
{
theFullPath = theFullPath.Substring(0,theFullPath.Length-1);
}
// insert the path in the text box
txtTargetDir.Text = theFullPath;
}

}//close for public class Form1 : System.Windows.Forms.Form
}//close for namespace FileCopier

/* <eof> */
-t-

-- modified at 22:25 Sunday 4th June, 2006
QuestionWhat is wrong with this query ? Pin
TheBeginner774-Jun-06 1:01
TheBeginner774-Jun-06 1:01 
AnswerRe: What is wrong with this query ? Pin
Hesham Amin4-Jun-06 1:19
Hesham Amin4-Jun-06 1:19 
AnswerRe: What is wrong with this query ? Pin
Nicholas Butler4-Jun-06 1:22
sitebuilderNicholas Butler4-Jun-06 1:22 
Questionvery very urgent COM PORT Pin
mohdmeraj3-Jun-06 22:58
mohdmeraj3-Jun-06 22:58 
AnswerRe: very very urgent COM PORT Pin
leppie3-Jun-06 23:23
leppie3-Jun-06 23:23 
AnswerRe: very very urgent COM PORT Pin
Ravi Bhavnani4-Jun-06 7:26
professionalRavi Bhavnani4-Jun-06 7:26 
Questionquery statement Pin
foysal mamun3-Jun-06 22:23
foysal mamun3-Jun-06 22:23 
AnswerRe: query statement Pin
Tamimi - Code3-Jun-06 22:32
Tamimi - Code3-Jun-06 22:32 
GeneralRe: query statement Pin
foysal mamun3-Jun-06 22:40
foysal mamun3-Jun-06 22:40 
GeneralRe: query statement Pin
Tamimi - Code3-Jun-06 22:46
Tamimi - Code3-Jun-06 22:46 
AnswerRe: query statement Pin
Laubi3-Jun-06 23:14
Laubi3-Jun-06 23:14 
AnswerRe: query statement Pin
Tamimi - Code3-Jun-06 23:21
Tamimi - Code3-Jun-06 23:21 
AnswerRe: query statement Pin
Hesham Amin4-Jun-06 1:22
Hesham Amin4-Jun-06 1:22 
AnswerRe: query statement Pin
Stephan Samuel4-Jun-06 3:09
Stephan Samuel4-Jun-06 3:09 
QuestionTooltip question Pin
martin_hughes3-Jun-06 15:02
martin_hughes3-Jun-06 15:02 
AnswerRe: Tooltip question Pin
MoustafaS3-Jun-06 19:41
MoustafaS3-Jun-06 19:41 
AnswerRe: Tooltip question Pin
Tamimi - Code3-Jun-06 19:54
Tamimi - Code3-Jun-06 19:54 

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.