I am working in C# WinForms. I have made a Windows Explorer that displays the logical directories and then when clicked on them, it shows the files in them in a ListView (old but tricky thing). I get the icons from the system, using:
Icon iconForFile = SystemIcons.WinLogo;
ListViewItem lv = new ListViewItem(filData, imageList1.Images.Count);
lv.Tag = file;
iconForFile = Icon.ExtractAssociatedIcon(file);
string Extension = Path.GetExtension(file);
if (!imageList1.Images.ContainsKey(file))
{
// If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file);
imageList1.Images.Add(file, iconForFile);
}
lv.ImageKey = file;
listView1.SmallImageList = imageList1;
Now the problem is this: it does show the icons when a directory at first-level is clicked but when I click the folders in any directory (ie. "C"), it doesn't show the icons in the subfolders of a directory. Please help me on how I can customize it. My full code is somewhat like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
PopulateTreeView(treeView1);
}
private void PopulateTreeView(TreeView tv)
{
string[] drives = Environment.GetLogicalDrives();
TreeNode MyCnode = new TreeNode();
MyCnode = new TreeNode("My Computer");
tv.Nodes.Add(MyCnode);
foreach (string drive in drives)
{
TreeNode nodeDrive = new TreeNode();
nodeDrive.Tag = drive;
nodeDrive.Text = drive;
tv.Nodes.Add(nodeDrive);
// tv.Nodes.Add();
// nodeDrive.EnsureVisible();
// treeView1.Refresh();
try
{
//add dirs under drive
if (Directory.Exists(drive))
{
foreach (string dir in Directory.GetDirectories(drive))
{
TreeNode node = new TreeNode();
node.Tag = dir;
node.Text = dir.Substring(dir.LastIndexOf(#"\") + 1);
node.ImageIndex = 1;
nodeDrive.Nodes.Add(node);
}
}
}
catch (Exception)
{
}
MyCnode.Expand();
}
}
public TreeNode GetDirectory(TreeNode parentNode)
{
DirectoryInfo d = new DirectoryInfo(parentNode.FullPath);
DirectoryInfo[] dInfo = d.GetDirectories()
.Where(di => !di.Attributes.HasFlag(FileAttributes.System))
.Where(di => !di.Attributes.HasFlag(FileAttributes.Hidden))
.ToArray();
parentNode.Nodes.Clear();
if (dInfo.Length > 0)
{
TreeNode treeNode = new TreeNode();
foreach (DirectoryInfo driSub in dInfo)
{
treeNode = parentNode.Nodes.Add(driSub.Name);
treeNode.Nodes.Add("");
}
}
return parentNode;
}
private void AddFiles(string strPath)
{
try
{
listView1.BeginUpdate();
listView1.Items.Clear();
//headers listview
// listView1.Columns.Add("File Name", 200);
//listView1.Columns.Add("Size", 80);
//listView1.Columns.Add("Last Accessed", 110);
string[] dirData = new string[3];
string[] filData = new string[3];
string[] files = Directory.GetFiles(strPath);
foreach (string file in files)
{
FileInfo finfo = new FileInfo(file);
FileAttributes fatr = finfo.Attributes;
string name = Path.GetFileNameWithoutExtension(file);
filData[0] = name;
filData[1] = finfo.Length.ToString();
filData[2] = File.GetLastAccessTime(file).ToString();
// Set a default icon for the file.
Icon iconForFile = SystemIcons.WinLogo;
ListViewItem lv = new ListViewItem(filData, imageList1.Images.Count);
lv.Tag = file;
iconForFile = Icon.ExtractAssociatedIcon(file);
string Extension = Path.GetExtension(file);
if (!imageList1.Images.ContainsKey(file))
{
// If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file);
imageList1.Images.Add(file, iconForFile);
}
lv.ImageKey = file;
listView1.SmallImageList = imageList1;
listView1.Items.Add(lv);
}
}
catch (Exception Exc) { MessageBox.Show(Exc.ToString()); }
listView1.EndUpdate();
}
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string pathdoubleClicked = listView1.FocusedItem.Tag.ToString();
Process.Start(pathdoubleClicked);
}
private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
{
GetDirectory(e.Node);
treeView1.SelectedNode.Expand();
AddFiles(e.Node.FullPath.ToString());
}
}
for anyone still seeing this as an answer to a search, the assignment of the imagelist needs to be done before the items are added to the imagelist.
private void AddFiles(string strPath)
{
try
{
listView1.BeginUpdate();
listView1.Items.Clear();
listView1.SmallImageList = imageList1;
Related
I have a TreeView that shows all the folders on the computer.
How can I see all the files within a particular folder that in the TreeView?
try this:
private void button1_Click(object sender, EventArgs e)
{
treeView1.ShowNodeToolTips = true;
DirectoryInfo d = new DirectoryInfo("C:\\projects");
GetAllDirectories(d, null);
}
void GetAllDirectories(DirectoryInfo d, TreeNode nodeToAddChilds)
{
if (treeView1.Nodes.Count == 0)
{
TreeNode root = new TreeNode();
root.ToolTipText = GetFileNames(d);
root.Text = d.Name;
treeView1.Nodes.Add(root);
nodeToAddChilds = root;
}
DirectoryInfo[] dirList = d.GetDirectories();
foreach (DirectoryInfo oneDir in dirList)
{
if (oneDir.Name.StartsWith("$"))
{
// Just to avoid system permission limitations
continue;
}
TreeNode newChild = new TreeNode();
newChild.ToolTipText = GetFileNames(oneDir);
newChild.Text = oneDir.Name;
nodeToAddChilds.Nodes.Add(newChild);
GetAllDirectories(oneDir, newChild);
}
}
string GetFileNames(DirectoryInfo d)
{
string files = "files:\r\n";
FileInfo[] allFiles = d.GetFiles();
foreach (FileInfo oneFile in allFiles)
{
files += oneFile.Name + "\r\n";
}
return files;
}
private void treeView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
// Get the selected node.
TreeNode node = treeView1.SelectedNode;
DirectoryInfo d = new DirectoryInfo(node.text);
FileInfo[] Files = d.GetFiles();
}
I am writing a code in C# to show the unknown number of images from a specified folder into a "listview" I don't know how to get all the files present in that specific folder.
I know I have to use a loop and array but I don't know how.
Here is the code which I use to access files with the "known name of file".
It's a windows form app.
private void btnZoom_Click(object sender, EventArgs e)
{
ImageList imgs = new ImageList();
imgs.ImageSize = new Size(100, 100);
string[] paths = { };
paths = Directory.GetFiles("TestFolder");
try
{
foreach (string path in paths)
{
imgs.Images.Add(Image.FromFile(path));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
listView1.SmallImageList = imgs;
listView1.Items.Add("2",0);
}
To get all the image files you can do
IEnumerable<string> paths = Directory.GetFiles(#"Your Dir", "*.*").Where(x=>x.EndsWith(".png") || x.EndsWith(".jpg")); //add all the extensions you wish in
then you can just iterate thru the list to add them in
Here is the working code:
and the code is :
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
imageList1.Images.Clear();
string[] pics = System.IO.Directory.GetFiles( "pics//");
listView1.View = View.SmallIcon;
listView1.SmallImageList = imageList1;
imageList1.ImageSize = new Size(64, 64);
foreach (string pic in pics)
{
imageList1.Images.Add(Image.FromFile(pic));
}
for (int j = 0; j < imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
listView1.Items.Add(item);
}
}
and at designer set this:
So far I have created a File Explorer - however I want to add a button which will allow the selected file to be opened when clicked. I've heard about the OpenFileDialog but it only seems to show a directory which I don't want. Any ideas? This is the code I've got, using C#.
namespace SynchronizeTaskPaneAndRibbon
{
public partial class FileChooser : UserControl
{
private void PopulateTreeView()
{
TreeNode rootNode;
DirectoryInfo info = new DirectoryInfo(#"../..");
if (info.Exists)
{
rootNode = new TreeNode(info.Name);
rootNode.Tag = info;
GetDirectories(info.GetDirectories(), rootNode);
treeView1.Nodes.Add(rootNode);
}
}
private void GetDirectories(DirectoryInfo[] subDirs, TreeNode nodeToAddTo)
{
TreeNode aNode;
DirectoryInfo[] subSubDirs;
foreach (DirectoryInfo subDir in subDirs)
{
aNode = new TreeNode(subDir.Name, 0, 0);
aNode.Tag = subDir;
aNode.ImageKey = "folder";
try
{
subSubDirs = subDir.GetDirectories();
}
catch (System.UnauthorizedAccessException)
{
subSubDirs = new DirectoryInfo[0];
}
if (subSubDirs.Length != 0)
{
GetDirectories(subSubDirs, aNode);
}
nodeToAddTo.Nodes.Add(aNode);
}
}
public FileChooser()
{
InitializeComponent();
PopulateTreeView();
this.treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
}
void treeView1_NodeMouseClick(object sender,TreeNodeMouseClickEventArgs e)
{
TreeNode newSelected = e.Node;
listView1.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
foreach (DirectoryInfo dir in nodeDirInfo.GetDirectories())
{
item = new ListViewItem(dir.Name, 0);
subItems = new ListViewItem.ListViewSubItem[]
{new ListViewItem.ListViewSubItem(item, "Directory"),
new ListViewItem.ListViewSubItem(item,
dir.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
}
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
if (file.Extension == ".xlsx" || file.Extension == ".xls" || file.Extension == ".xlsm" || file.Extension == ".csv")
{
item = new ListViewItem(file.Name, 1);
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
}
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
First, when creating the ListViewItems, I'd add the full path of the file to the .Tag so you can retrieve it easily:
item.Tag = file.FullName;
Then you'd use something like this in a button click event:
private void button1_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
foreach(ListViewItem lvi in listView1.SelectedItems)
{
if (lvi.Tag != null && lvi.Tag is string)
{
string fullPathFile = lvi.Tag.ToString();
try
{
Process.Start(fullPathFile);
}
catch (Exception ex)
{
MessageBox.Show("FileName: " + fullPathFile + "\r\n\r\n" + ex.ToString(), "Error Opening File");
}
}
}
}
}
I created a function in a Windows Form Application that allows users to view a folder structure (TreeForm) and the files within the folders in a ListView. Now, I need to create the same function for a WebForm application. I attempted to use the same code but have found that the asp.net webform controls do not contain the same properties as the winform. Below is part of the code which I cannot determine how to convert so that it maybe used with on a webform page. Does anyone now how to convert the following code so that it can be used with an asp.net webform? Any assistance would be greatly appreciated.
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
ListView1.Items.Clear();
ListViewItem.ListViewSubItem[] subItems;
List<string> permittedFoldersFiles = new List<string>();
if (permittedFoldersFiles.Contains(dir.Name))
{
item = new ListViewItem(dir.Name, 0);
subItems = new ListViewItem.ListViewSubItem[]
{new ListViewItem.ListViewSubItem(item, "Directory"),
new ListViewItem.ListViewSubItem(item,
dir.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
}
Try use this sample it's work very well
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DirectoryInfo rootInfo = new DirectoryInfo(Server.MapPath("~/MyFolder/"));
this.PopulateTreeView(rootInfo, null);
}
}
private void PopulateTreeView(DirectoryInfo dirInfo, TreeNode treeNode)
{
foreach (DirectoryInfo directory in dirInfo.GetDirectories())
{
TreeNode directoryNode = new TreeNode
{
Text = directory.Name,
Value = directory.FullName
};
if (treeNode == null)
{
//If Root Node, add to TreeView.
TreeView1.Nodes.Add(directoryNode);
}
else
{
//If Child Node, add to Parent Node.
treeNode.ChildNodes.Add(directoryNode);
}
//Get all files in the Directory.
foreach (FileInfo file in directory.GetFiles())
{
//Add each file as Child Node.
TreeNode fileNode = new TreeNode
{
Text = file.Name,
Value = file.FullName,
Target = "_blank",
NavigateUrl = (new Uri(Server.MapPath("~/"))).MakeRelativeUri(new Uri(file.FullName)).ToString()
};
directoryNode.ChildNodes.Add(fileNode);
}
PopulateTreeView(directory, directoryNode);
}
}
I get this error when I try to add items to an array, it adds with no problem 1 items, but when there are more it stops and gives an error.
nullReferenceException
Object reference not set to an instance of an object.
public void btnZoek_Click(object sender, EventArgs e)
{
if (search == false)
{
OpenFiles[index] = new AddFileClass();
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Saves");
System.IO.FileInfo[] rgFiles = di.GetFiles("*.txt");//add only .txt files
foreach (System.IO.FileInfo fi in rgFiles)
{
OpenFiles[index].setNewItem(index, fi.Name, Convert.ToString(di));//send the info to the array (Number, filename, filelocation)
index++;
}
search = true; //make sure it doens'nt add something double
}
if (search == true)
{
Form3_Zoeken_ frmSearch = new Form3_Zoeken_();
frmSearch.Show();
}
}
here is a pic to show that the fi(FileInfo) and di(DirectoryInfo) are not empty:
It looks to me that you never initialize the OpenFiles array items - that is, you only initialize the first item.
Try this:
public void btnZoek_Click(object sender, EventArgs e)
{
if (search == false)
{
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Saves");
System.IO.FileInfo[] rgFiles = di.GetFiles("*.txt");//add only .txt files
foreach (System.IO.FileInfo fi in rgFiles)
{
OpenFiles[index] = new AddFileClass();
OpenFiles[index].setNewItem(index, fi.Name, Convert.ToString(di));//send the info to the array (Number, filename, filelocation)
index++;
}
search = true; //make sure it doens'nt add something double
}
if (search == true)
{
Form3_Zoeken_ frmSearch = new Form3_Zoeken_();
frmSearch.Show();
}
}