Thursday, August 21, 2008

Browse Folder and File

using C#.Net 2.0
3 types of codings are there in 3 models


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Deployment;
using System.Diagnostics;
using System.DirectoryServices;
namespace TreeDir
{
public partial class Form1 : Form
{
// private DirectoryInfo folder;
private static string driveLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public string flname;
public Form1()
{
InitializeComponent();
}
private void fillTree()
{
DirectoryInfo directory;
string sCurPath = "";

treeView1.Nodes.Clear();

foreach (char c in driveLetters)
{
sCurPath = c + ":\\";
try
{
directory = new DirectoryInfo(sCurPath);

if (directory.Exists == true)
{
TreeNode newNode = new TreeNode(directory.FullName);
treeView1.Nodes.Add(newNode); // add the new node to the root level.
getSubDirs(newNode); // scan for any sub folders on this drive.
}
}
catch (Exception doh)
{
Console.WriteLine(doh.Message);
}
}
}
private void getSubDirs(TreeNode parent)
{
DirectoryInfo directory;
FolderBrowserDialog dlg = new FolderBrowserDialog();

try
{

if (parent.Nodes.Count == 0)
{
directory = new DirectoryInfo(parent.FullPath);
foreach (DirectoryInfo dir in directory.GetDirectories())
{

TreeNode newNode = new TreeNode(dir.Name);
parent.Nodes.Add(newNode);
}
}


foreach (TreeNode node in parent.Nodes)
{

if (node.Nodes.Count == 0)
{

directory = new DirectoryInfo(node.FullPath);

foreach (DirectoryInfo dir in directory.GetDirectories())
{
TreeNode newNode = new TreeNode(dir.Name);
node.Nodes.Add(newNode);
}
}
}
}
catch (Exception doh)
{
Console.WriteLine(doh.Message);
}
}

private void button1_Click(object sender, EventArgs e)
{
//try { Directory.CreateDirectory(@"e:\qwe1"); } catch (Exception ex) {label1.Text = ex.Message; }
// DirectoryInfo dr;

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
string[] dirinfo = Directory.GetDirectories(textBox1.Text);
string parentpath = new FileInfo(textBox1.Text).Name;
// string[] dirinfo = Directory.GetFileSystemEntries(@"e:\1");

TreeNode mainnode = new TreeNode(textBox1.Text);

treeView1.Nodes.Add(mainnode);

//treeView1.Nodes.Add(treeView1, "asd");

TreeNode tn = new TreeNode();

foreach (string str in dirinfo)
{
if (Directory.Exists(str))
{
try
{
tn = mainnode.Nodes.Add(str);
// MessageBox.Show("node added" + str, "tn");
ProcessDirectory(tn, str);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
else
{
if (File.Exists(str))
ProcessFile(mainnode, str);
}

}
}
}
public static void ProcessFile(TreeNode pn, string path)
{
pn.Nodes.Add(path);
//Console.WriteLine("Processed file '{0}'.", path);
}

public static void ProcessDirectory(TreeNode parentnode, string targetDirectory)
{
try
{

TreeNode pn = new TreeNode();

// MessageBox.Show("node added" + targetDirectory, "pn");

// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(parentnode, fileName);

// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
pn = parentnode.Nodes.Add(targetDirectory);
ProcessDirectory(pn, subdirectory);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

private Word.ApplicationClass WordApp = new Word.ApplicationClass();

private void button2_Click(object sender, EventArgs e)
{
fillTree();

}

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
////System.Diagnostics.Process.Start("e:\\conv");

//// Use the open file dialog to choose a word document
//// if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
//{
// // set the file name from the open file dialog
// object fileName = treeView1.SelectedNode.Text;// openFileDialog1.FileName;
// object readOnly = false;
// object isVisible = true;
// // Here is the way to handle parameters you don't care about in .NET
// object missing = System.Reflection.Missing.Value;
// // Make word visible, so you can see what's happening
// WordApp.Visible = true;
// // Open the document that was chosen by the dialog
// Word.Document aDoc = WordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
// // Activate the document so it shows up in front
// aDoc.Activate();
// // Add the copyright text and a line break
// //WordApp.Selection.TypeText("Copyright C# Corner");
// WordApp.Selection.TypeParagraph();
//}

}

private void button3_Click(object sender, EventArgs e)
{

Form2 obj = new Form2();
obj.Show();
}

private void Form1_Load(object sender, EventArgs e)
{

}
/*
# region
private ListDictionary m_StatusIcons;
public ListDictionary StatusIcons
{
get
{
return m_StatusIcons;
}

set
{
m_StatusIcons = value;
}
}

private void RenderTree()
{
ImageTreeViewNode type1Node = new ImageTreeViewNode();

type1Node.Text = "I am an ImageTreeViewNode";

ListDictionary StatusIcons = new ListDictionary();
StatusIcons.Add("i am icon type 1", "icon1.png");
StatusIcons.Add("hi there, i am icon type 2", "icon2.png");

type1Node.StatusIcons = StatusIcons;

TreeView1.Nodes.Add(type1Node);

}
# endregion
*/
private void button4_Click(object sender, EventArgs e)
{
ImageList li = new ImageList();
li.ImageSize = new Size(32, 32);
li.ColorDepth = ColorDepth.Depth32Bit;
treeView1.ImageList = li;

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Application.StartupPath + @"\images");
foreach (System.IO.FileInfo file in dir.GetFiles("*.*"))
{
li.Images.Add(Image.FromFile(@"images\" + file.Name));
treeView1.Nodes.Add(null, file.Name, file.Name.ToString(), file.Name.ToString());
}
}


}
}

------------------------------

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

namespace TreeDir
{
public partial class Form3 : Form
{
private bool ListItems = false;
private string CurrentParentPath;

public Form3()
{
InitializeComponent();

tbFolder.KeyPress +=
new KeyPressEventHandler(OnTextBoxKeyPress);
listFileItems.SelectedIndexChanged +=
new EventHandler(OnlistFileItemSelected);
listFolderItems.SelectedIndexChanged +=
new EventHandler(OnlistFolderItemsSelected);
buttonUp1.Click +=
new EventHandler(OnUpButtonClick);
}
#region EventHandlers

protected void OnTextBoxKeyPress(object Sender, KeyPressEventArgs e)
{
if ((int)e.KeyChar == 13 && ListItems == false)
ProcessFolder(tbFolder.Text);
}

protected void OnUpButtonClick(object Sender, EventArgs e)
{
string ParentPath = new FileInfo(CurrentParentPath).DirectoryName;
// ProcessFolder(ParentPath);
ProcessFolder(CurrentParentPath);
// MessageBox.Show(ParentPath.ToString());
}

protected void OnlistFileItemSelected(object Sender, EventArgs e)
{
string SelectedString = listFileItems.SelectedItem.ToString();
string FullPathName = Path.Combine(CurrentParentPath, SelectedString);
ProcessFile(FullPathName);

}
protected void OnlistFolderItemsSelected(object Sender, EventArgs e)
{
string SelectedString = listFolderItems.SelectedItem.ToString();
string FullPathName = Path.Combine(CurrentParentPath, SelectedString);
ProcessFolder(FullPathName);
}
#endregion
protected void ProcessFolder(string PathName)
{
try
{
ClearAllFields();
ListItems = true;
DirectoryInfo TheFolder = new DirectoryInfo(PathName);
if (TheFolder.Exists)
{
ListContentsOfFolder(TheFolder);
return;
}
else

{
MessageBox.Show("Folder Not Found");
}

throw new FileNotFoundException();
}
catch (FileNotFoundException)
{
tbFolder.Text = PathName;
listFolderItems.Items.Add("This folder or folder does not exist");
}
catch (Exception e)
{
tbFolder.Text = PathName;
listFolderItems.Items.Add("Problem occurred:");
listFolderItems.Items.Add(e.Message);
}
finally
{
ListItems = false;
}
}
protected void ProcessFile(string PathName)
{
try
{
ClearAllFields();
ListItems = true;
FileInfo TheFile = new FileInfo(PathName);
if (TheFile.Exists)
{
DirectoryInfo Parent = TheFile.Directory;
ListContentsOfFolder(Parent);
DisplayFileInfo(TheFile);
return;
}
throw new FileNotFoundException();
}
catch (FileNotFoundException)
{
tbFolder.Text = PathName;
listFileItems.Items.Add("This file or folder does not exist");
}
catch (Exception e)
{
tbFolder.Text = PathName;
listFileItems.Items.Add("Error Processing");
listFileItems.Items.Add(e.Message);
}
finally
{
ListItems = false;
}
}

protected void DisplayFileInfo(FileInfo TheFile)
{
tbFileName.Text = TheFile.Name;
tbCreationTime.Text = TheFile.CreationTime.ToLongTimeString();
tbLastAccessTime.Text = TheFile.LastAccessTime.ToLongDateString();
tbLastWriteTime.Text = TheFile.LastWriteTime.ToLongDateString();
tbSize.Text = TheFile.Length.ToString() + " Bytes";
}

protected void ListContentsOfFolder(DirectoryInfo Parent)
{
CurrentParentPath = Parent.FullName;
tbFolder.Text = CurrentParentPath;

foreach (FileInfo NextFile in Parent.GetFiles())
{
listFileItems.Items.Add(NextFile.Name);
}
foreach (DirectoryInfo NextFolder in Parent.GetDirectories())
{
listFolderItems.Items.Add(NextFolder.Name);
}
}

protected void ClearAllFields()
{
listFileItems.Items.Clear();
listFolderItems.Items.Clear();
tbFolder.Text = "";
tbFileName.Text = "";
tbCreationTime.Text = "";
tbLastAccessTime.Text = "";
tbLastWriteTime.Text = "";
tbSize.Text = "";
}

private void button1_Click(object sender, EventArgs e)
{


if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
buttonUp.Text = folderBrowserDialog1.SelectedPath;
CurrentParentPath = buttonUp.Text;

}
}

private void button1_Click_1(object sender, EventArgs e)
{
if(CurrentParentPath != null)
{
if (CurrentParentPath != Directory.GetDirectoryRoot(CurrentParentPath))
{
string ParentPath = new FileInfo(CurrentParentPath).DirectoryName;
ProcessFolder(ParentPath);
buttonUp.Text = ParentPath;

}
else
{
MessageBox.Show("No Parent Found");
}
}
else
{
MessageBox.Show("Path Not Found");
}


//ProcessFolder(CurrentParentPath);
}

private void button2_Click(object sender, EventArgs e)
{
Form1 obj = new Form1();
obj.Show();
}
}
}

----------------------------------

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

namespace TreeDir
{
public partial class Form2 : Form
{
private DirectoryInfo folder;
private static string driveLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public Form2()
{
InitializeComponent();
fillTree();
}

private void fillTree()
{
DirectoryInfo directory;
string sCurPath = "";

treeView1.Nodes.Clear();

foreach( char c in driveLetters )
{
sCurPath = c + ":\\";
try
{
directory = new DirectoryInfo(sCurPath);

if ( directory.Exists == true )
{
TreeNode newNode = new TreeNode(directory.FullName);
treeView1.Nodes.Add(newNode); // add the new node to the root level.
getSubDirs(newNode); // scan for any sub folders on this drive.
}
}
catch( Exception doh)
{
Console.WriteLine(doh.Message);
}
}
}

private void getSubDirs( TreeNode parent )
{
DirectoryInfo directory;
FolderBrowserDialog dlg = new FolderBrowserDialog();
try
{

if ( parent.Nodes.Count == 0 )
{
directory = new DirectoryInfo(parent.FullPath);
foreach( DirectoryInfo dir in directory.GetDirectories())
{
TreeNode newNode = new TreeNode(dir.Name);
parent.Nodes.Add(newNode);
}
}

foreach(TreeNode node in parent.Nodes)
{

if (node.Nodes.Count == 0)
{

directory = new DirectoryInfo(node.FullPath);

foreach( DirectoryInfo dir in directory.GetDirectories())
{
TreeNode newNode = new TreeNode(dir.Name);
node.Nodes.Add(newNode);
}
}
}
}
catch( Exception doh )
{
Console.WriteLine(doh.Message);
}
}

private string fixPath( TreeNode node )
{
string sRet = "";
try
{
sRet = node.FullPath;
int index = sRet.IndexOf("\\\\");
if (index > 1 )
{
sRet = node.FullPath.Remove(index, 1);
}
}
catch( Exception doh )
{
Console.WriteLine(doh.Message);
}
return sRet;
}

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

private void treeView1_BeforeSelect(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
{
getSubDirs(e.Node); // get the sub-folders for the selected node.
textBox1.Text = fixPath(e.Node); // update the user selection text box.
folder = new DirectoryInfo(e.Node.FullPath); // get it's Directory info.
}

private void treeView1_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
{
getSubDirs(e.Node); // get the sub-folders for the selected node.
textBox1.Text = fixPath(e.Node); // update the user selection text box.
folder = new DirectoryInfo(e.Node.FullPath); // get it's Directory info.
}

private void cancelBtn_Click(object sender, System.EventArgs e)
{
folder = null;
this.Close();
}

private void selectBtn_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}

public string name
{
get { return ((folder != null && folder.Exists)) ? folder.Name : null; }
}

public string fullPath
{
get { return ((folder != null && folder.Exists && treeView1.SelectedNode != null)) ? fixPath(treeView1.SelectedNode) : null; }
}

public DirectoryInfo info
{
get { return ((folder != null && folder.Exists)) ? folder : null; }
}

private void button2_Click(object sender, EventArgs e)
{
Form1 obj = new Form1();
obj.Show();
}

private void button3_Click(object sender, EventArgs e)
{
Form3 obj = new Form3();
obj.Show();
}
}

No comments: