I'm needing a way to allow the files that are displayed in the ListView to be opened. The Items In the ListView are displayed from the TreeView. Take a look at my code below to see in more detail.
Code for this form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace OSTP
{
public partial class User1FileExplorer : Form
{
public User1FileExplorer()
{
InitializeComponent();
PopulateTreeView();
this.treeView1.NodeMouseClick +=
new TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
}
private void User1FileExplorer_Load(object sender, EventArgs e)
{
}
private void PopulateTreeView()
{
TreeNode rootNode;
DirectoryInfo info = new DirectoryInfo(#"C:\Users\Oliver\Documents\.OSTP\User1\Files\Documents");
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";
subSubDirs = subDir.GetDirectories();
if (subSubDirs.Length != 0)
{
GetDirectories(subSubDirs, aNode);
}
nodeToAddTo.Nodes.Add(aNode);
}
}
private 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);
listView1.Items.Add(item);
}
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
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);
}
}
}
As you can see from my code I use a TreeView to select the directory for the files then the ListView to display the files inside of the directory.
I would like it so when the user double clicks the file in the ListView it opens. And when I say open I'm not meaning open a text file as such. So lets say the user double clicks text file 1 in the ListView, I would like it to show User1TextFile1.cs. This is because the text files are loaded into a text box.
I know this is a little complicated, so If I have missed anything please drop a comment.
Thanks.
UPDATE
http://pastebin.com/BgVdLavL
UPDATE2
When I add MessageBox.Show("" + lvHti);
To find out which ListViewItem was clicked or doubleclicked use the MouseClick or the MouseDoubleClick event.
Here you can either code simply:
ListViewItem lvItem = null;
if (listView1.SelectedItems.Count > 0)
lvItem = listView1.SelectedItems[0];
provided the ListView has MultiSelect = false.
If you allow multiple selections you need to do a HitTest to find out where the user has clicked:
ListViewItem lvItem = null;
ListViewHitTestInfo lvHti = listView1.HitTest(e.Location);
if (lvHti.Item != null) lvItem = lvHti.Item;
Now you can access the Item and/or its SubItems to process the choice.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Iam trying to get all drives, folders, subfolders and files in treeview control using winforms. I have seen the following article.
http://codehill.com/2013/06/list-drives-and-folders-in-a-treeview-using-c/
but this only shows drives, folders and sub folders but not the files containing in these folders.
Please anyone help and guide that how can i view all these files under these folders in treeview, thanks in advance.
EDIT:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GetDrives
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//get a list of the drives
string[] drives = Environment.GetLogicalDrives();
foreach (string drive in drives)
{
DriveInfo di = new DriveInfo(drive);
int driveImage;
switch (di.DriveType) //set the drive's icon
{
case DriveType.CDRom:
driveImage = 3;
break;
case DriveType.Network:
driveImage = 6;
break;
case DriveType.NoRootDirectory:
driveImage = 8;
break;
case DriveType.Unknown:
driveImage = 8;
break;
default:
driveImage = 2;
break;
}
TreeNode node = new TreeNode(drive.Substring(0, 1), driveImage, driveImage);
node.Tag = drive;
if (di.IsReady == true)
node.Nodes.Add("...");
dirsTreeView.Nodes.Add(node);
}
}
private void dirsTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Nodes.Count > 0)
{
if (e.Node.Nodes[0].Text == "..." && e.Node.Nodes[0].Tag == null)
{
e.Node.Nodes.Clear();
//get the list of sub direcotires
string[] dirs = Directory.GetDirectories(e.Node.Tag.ToString());
foreach (string dir in dirs)
{
DirectoryInfo di = new DirectoryInfo(dir);
TreeNode node = new TreeNode(di.Name, 0, 1);
try
{
//keep the directory's full path in the tag for use later
node.Tag = dir;
//if the directory has sub directories add the place holder
if (di.GetDirectories().Count() > 0)
node.Nodes.Add(null, "...", 0, 0);
foreach (var file in di.GetFiles())
{
TreeNode n = new TreeNode(file.Name, 13, 13);
node.Nodes.Add(n);
}
}
catch (UnauthorizedAccessException)
{
//display a locked folder icon
node.ImageIndex = 12;
node.SelectedImageIndex = 12;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "DirectoryLister",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
e.Node.Nodes.Add(node);
}
}
}
}
}
}
}
I have now updated my code in application and using only one treeview, but the problem still exists. You can see in image, in my C drive i have a file name "courses outline.html" and ab.txt which are not showing in application, which i need to see. Please see iamge below to easily understand my requirement.
Change the code in the try block (from: List Drives and Folders in a TreeView Using C#) as following:
EDIT:
Added following code, because the files of the root-directory were ignored:
//add files of rootdirectory
DirectoryInfo rootDir = new DirectoryInfo(e.Node.Tag.ToString());
foreach (var file in rootDir.GetFiles())
{
TreeNode n = new TreeNode(file.Name, 13, 13);
e.Node.Nodes.Add(n);
}
Full class:
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Nodes.Count > 0)
{
if (e.Node.Nodes[0].Text == "..." && e.Node.Nodes[0].Tag == null)
{
e.Node.Nodes.Clear();
//get the list of sub direcotires
string[] dirs = Directory.GetDirectories(e.Node.Tag.ToString());
//add files of rootdirectory
DirectoryInfo rootDir = new DirectoryInfo(e.Node.Tag.ToString());
foreach (var file in rootDir.GetFiles())
{
TreeNode n = new TreeNode(file.Name, 13, 13);
e.Node.Nodes.Add(n);
}
foreach (string dir in dirs)
{
DirectoryInfo di = new DirectoryInfo(dir);
TreeNode node = new TreeNode(di.Name, 0, 1);
try
{
//keep the directory's full path in the tag for use later
node.Tag = dir;
//if the directory has sub directories add the place holder
if (di.GetDirectories().Count() > 0)
node.Nodes.Add(null, "...", 0, 0);
foreach (var file in di.GetFiles())
{
TreeNode n = new TreeNode(file.Name, 13, 13);
node.Nodes.Add(n);
}
}
catch (UnauthorizedAccessException)
{
//display a locked folder icon
node.ImageIndex = 12;
node.SelectedImageIndex = 12;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "DirectoryLister",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
e.Node.Nodes.Add(node);
}
}
}
}
}
This look like following picture:
You can use the enumerate files method to get the name of each file inside a directory location.
string sourceDirectory = #"C:\current";
var files = Directory.EnumerateFiles(sourceDirectory);
foreach (string file in files)
{
// Do Something with file
}
I'm creating a winform application wit C# and VS 2010 Ultimate. I'm populating a flowlayoutpanel with dynamically created comboxes, all databound to the same bindinglist.
When I run the application, it adds the comboxes correctly but when I select an item on one combobox, all the others are updated with the same selection.
What am I doing wrong?
Thanks very much for any help received.
J.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace TestCompleteForm
{
public partial class Form1 : Form
{
private int comboBoxIndex = 0;
List<string> Existingfiles;
BindingList<string> ExistingSystemsList;
List<string> Selectedfiles;
BindingList<string> SelectedSystemsList;
BindingList<string> ListOfLanguages = new BindingList<string>();
BindingList<string> ListOfSQLServers = new BindingList<string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Hosts");
FileInfo[] Files = dinfo.GetFiles("*.txt");
Existingfiles = new List<string>();
foreach (FileInfo file in Files)
{
Existingfiles.Add(Path.GetFileNameWithoutExtension(file.Name));
}
ExistingSystemsList = new BindingList<string>(Existingfiles);
lbAvailableSystems.DataSource = ExistingSystemsList;
Selectedfiles = new List<string>();
SelectedSystemsList = new BindingList<string>(Selectedfiles);
lbSelectedSystems.DataSource = SelectedSystemsList;
//Creat list of languages
var txtLanguages = File.ReadAllLines(#"C:\Languages\Languages.txt");
foreach (var s in txtLanguages) ListOfLanguages.Add(s);
//Creat list of sql servers
var txtSqlServers = File.ReadAllLines(#"C:\SQL Servers\sql-servers.txt");
foreach (var s in txtSqlServers) ListOfSQLServers.Add(s);
}
private void TabControl1_Click(object sender, EventArgs e)
{
if (tabControl1.SelectedTab.Name.ToString() == "page2")
{
while (flowLayoutPanel1.Controls.Count > 0)
{
var ControlToRemove = flowLayoutPanel1.Controls[0];
flowLayoutPanel1.Controls.Remove(ControlToRemove);
ControlToRemove.Dispose();
}
//flowLayoutPanel1.Controls.Clear();
foreach (string StrSystem in SelectedSystemsList)
{
Label lNewSystem = new Label();
lNewSystem.Text = StrSystem;
flowLayoutPanel1.Controls.Add(lNewSystem);
//Add combobox for languages
ComboBox cbLanguages = new ComboBox();
cbLanguages.Name = "cbLanguages" + comboBoxIndex.ToString();
cbLanguages.DataSource = ListOfLanguages;
flowLayoutPanel1.Controls.Add(cbLanguages);
//Add combobox for database servers
ComboBox cbSqlServers = new ComboBox();
cbSqlServers.Name = "cbSqlServers" + comboBoxIndex.ToString();
cbSqlServers.DataSource = ListOfSQLServers;
flowLayoutPanel1.Controls.Add(cbSqlServers);
comboBoxIndex++;
}
}
}
Ignore the bindinglist and use ComboBox.Items.Add() instead to add items to the control.
once again i have a problem that i can't quite seem to come up with a solution to. so here it is, I have a ListView displaying the directories of Image files,i want the listview to display these images for these files, the problem is I also need the images to be modified by the program at a per-pixel level so i have this done on a separate thread, so what i want to do is take my already existing PictureBox list of the modified Images and match up the names of the files with the corresponding image. Any ideas on how to do this?
here is what i have so far
public static List<PictureBox> ContentItems = new List<PictureBox>();
...
public static string ContentDirectory = "";
private void FileTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode newSelected = e.Node;
FileList.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
item = new ListViewItem(file.Name);
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
FileList.Items.Add(item);
}
FileList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
I Did have to use an image list after all Heres how i got it to work:
void FileTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode newSelected = e.Node;
FileList.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
ContentImg.Images.Clear();
int CurrentImg = 0;
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
string fileName = file.Name;
foreach (PictureBox PB in ContentItems)
{
if (fileName == PB.Name)
{
//Get Image
ContentImg.Images.Add(PB.Image);
item = new ListViewItem(file.Name, CurrentImg);
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
FileList.Items.Add(item);
CurrentImg += 1;
}
}
}
I Made an application to download a folder from a given sharepoint site, but its consuming memory above 600,000K once i click on Connect button, anyone can give suggestion to improve my code ?
I Tried to debug my form and problem is coming at method " private void MapWebs(SPWebCollection webList, TreeNode webparentNode)" where its calling itself again and again to go through each single web and its sub web, however I checked in the start when i click on connect and it goes through code line
using (SPSite CurrentSite = new SPSite(tbSite.Text))
The memory usage goes from 20,000 K to 40,000 K (approx)
In order to run this application you must have sharepoint installed on yur PC, an example of this type of app is on this link ,
enter link description here
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 Microsoft.SharePoint;
using System.IO;
namespace WindowsFormsApplication3
{
public partial class MainWindow : Form
{
public MainWindow()
{
InitializeComponent();
}
//Connects to Sharepoint site provided and populates Webs and Subwebs and subwebs....
private void bConnect_Click(object sender, EventArgs e)
{
//Getting current site
using (SPSite CurrentSite = new SPSite(tbSite.Text))
{
//Opening TopLevel Web for Site given
using (SPWeb TopLevelWeb = CurrentSite.OpenWeb())
{
//Clearing all the nodes in TreeWeb
TreeWeb.Nodes.Clear();
//Creating a root (First Node for webtree) which will be Top Level web's title
TreeNode rootWebNode = new TreeNode(TopLevelWeb.Title);
//Giving node a tag, which will be used later on in order to get value of node
rootWebNode.Tag = TopLevelWeb;
//Check if Top Level Web got any Sub webs if it does, it will create a new node for them
//Calls Map Webs to check for more sub webs + mapping them on webtree as nodes
foreach (SPWeb CurrentWeb in TopLevelWeb.Webs)
{
try
{
TreeNode webNode = new TreeNode(CurrentWeb.Title);
webNode.Tag = CurrentWeb;
MapWebs(CurrentWeb.Webs, webNode);
TreeWeb.Nodes.Add(webNode);
}
finally
{
if (CurrentWeb != null)
CurrentWeb.Dispose();
}
}
}
}
}
// Maps Webs and there sub webs on webtree
private void MapWebs(SPWebCollection webList, TreeNode webparentNode)
{
for (var i = 0; i < webList.Count; i++)
{
TreeNode node = new TreeNode(webList[i].Name);
using (SPWeb web = webList[i])
{
node.Tag = webList[i];
webparentNode.Nodes.Add(node);
if (webList[i].Webs.Count > 0)
MapWebs(webList[i].Webs, node);
}
}
GC.Collect();
}
//when the form loads it clears the list and create new cloumns to be used
private void MainWindow_Load(object sender, EventArgs e)
{
bFolder.Enabled = false;
bConnect.Enabled = false;
lvFiles.GridLines = true;
lvFiles.View = View.Details;
lvFiles.Columns.Add("Name", lvFiles.Width/4, HorizontalAlignment.Left);
lvFiles.Columns.Add("Date Created", lvFiles.Width/3, HorizontalAlignment.Left);
lvFiles.Columns.Add("Size", lvFiles.Width / 5, HorizontalAlignment.Left);
lvFiles.Columns.Add("Time Last Modified", lvFiles.Width / 5, HorizontalAlignment.Left);
if (lvFiles.View == View.Details && lvFiles.Columns.Count > 0)
this.Width = lvFiles.Columns.Count * (lvFiles.Width / 2);
lvFiles.Columns[lvFiles.Columns.Count - 1].Width = -2;
}
//creates directory for downloading folder
private bool CreateDirectoryStructure(string baseFolder, string filepath)
{
if (!Directory.Exists(baseFolder)) return false;
var paths = filepath.Split('/');
for (var i = 0; i < paths.Length - 1; i++)
{
baseFolder = System.IO.Path.Combine(baseFolder, paths[i]);
Directory.CreateDirectory(baseFolder);
}
return true;
}
//opens an dialog box for selecting path where selected folder will be downloaded
private void bBrowse_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
this.tbDirectory.Text = folderBrowserDialog1.SelectedPath;
}
}
//when a node is selected in webtree it checks for folders in it , + sub folders + folders......
private void TreeWeb_AfterSelect(object sender, TreeViewEventArgs e)
{
TreeFolder.Nodes.Clear();
TreeNode currentNode = TreeWeb.SelectedNode;
using (SPWeb oWeb = (SPWeb)currentNode.Tag)
{
foreach (SPList list in oWeb.Lists)
{
if (list is SPDocumentLibrary && !list.Hidden)
{
TreeNode folderNode = new TreeNode(list.Title);
folderNode.Text = string.Format("{0} ({1})", list.Title, list.ItemCount);
folderNode.Tag = list.RootFolder;
foreach (SPListItem listItem in list.Folders)
{
if (listItem.Folder != null)
{
TreeNode node = new TreeNode(listItem.Folder.Name);
node.Tag = listItem.Folder;
node.Text = string.Format("{0} ({1})", listItem.Folder.Name,
GetFilesCount(listItem.Folder));
MapFolders(listItem.Folder.SubFolders, node);
folderNode.Nodes.Add(node);
}
}
TreeFolder.Nodes.Add(folderNode);
}
}
}
}
//Maps folder on foldertree
private void MapFolders(SPFolderCollection folderList, TreeNode parentNode)
{
for (var i = 0; i < folderList.Count; i++)
{
TreeNode node = new TreeNode(folderList[i].Name);
node.Text = string.Format("{0} ({1})", folderList[i].Name,
GetFilesCount(folderList[i]));
node.Tag = folderList[i];
parentNode.Nodes.Add(node);
if (folderList[i].SubFolders.Count > 0)
MapFolders(folderList[i].SubFolders, node);
}
}
//Maps files in a folder to listview
private void TreeFolder_AfterSelect(object sender, TreeViewEventArgs e)
{
lvFiles.Items.Clear();
TreeNode currentNode = TreeFolder.SelectedNode;
//if (currentNode != rotnode)
//{
double TotalSize = 0;
SPFolder oFolder = (SPFolder)currentNode.Tag;
foreach (SPFile oFile in oFolder.Files)
{
TotalSize += (oFile.Length)/1024/1024;
ListViewItem LTI = new ListViewItem(oFile.Name.ToString());
LTI.SubItems.Add(oFile.TimeCreated.ToString());
LTI.SubItems.Add(oFile.Length.ToString());
LTI.SubItems.Add(oFile.TimeLastModified.ToString());
lvFiles.Items.Add(LTI);
}
label4.Text = TotalSize.ToString();
//}
}
//download selected folder + validation
private void bFolder_Click(object sender, EventArgs e)
{
TreeNode currentNode = TreeFolder.SelectedNode;
SPFolder oFolder = (SPFolder)currentNode.Tag;
foreach (SPFile file in oFolder.Files)
{
if (CreateDirectoryStructure(tbDirectory.Text, file.Url))
{
var filepath = System.IO.Path.Combine(tbDirectory.Text, file.Url);
byte[] binFile = file.OpenBinary();
System.IO.FileStream fstream = System.IO.File.Create(filepath);
fstream.Write(binFile, 0, binFile.Length);
fstream.Close();
}
}
}
//calculates files in selected folder
private int GetFilesCount(SPFolder folder)
{
int fileCount = folder.Files.Count;
foreach (SPFolder subfolder in folder.SubFolders)
{
fileCount += GetFilesCount(subfolder);
}
return fileCount;
}
//validation
private void tbSite_TextChanged(object sender, EventArgs e)
{
if (tbSite.Text != "")
bConnect.Enabled = true;
else
bConnect.Enabled = false;
}
//validation
private void tbDirectory_TextChanged(object sender, EventArgs e)
{
if (tbDirectory.Text != "" && TreeFolder.Nodes.Count != 0)
bFolder.Enabled = true;
else
bFolder.Enabled = false;
}
}
}
Already checked with SP Dispose checker but it says this (at MapWebs method line "node.tag = weblist[i]... and if statement")
Notes: Call to Microsoft.SharePoint.SPWebCollection.get_Item and no variable to catch return value
More Information: http://blogs.msdn.com/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx#SPDisposeCheckID_130
I see two issues here:
You are disposing the SPWeb while iterating over the SPWeb.Webs, but you keep a reference on the TreeNode.Tag. When accessing the disposed SPWeb via the tag of the node SharePoint will "open" the web again. => Memory Leak
Since you are calling the MapWebs method recursive you have a lot of SPWeb objects opened simultaneously:
Root -> open
Child 1 -> open
Child 1.1 -> open
Child 1.1.1 -> open
Child 1.2
Child 1.3
Child 1.4
Child 2
Child 3
I'm trying to create a context menu which will be able to add extra menu items, with an attached child menu, as required.
As it stands my code generates no errors and it will flow through the program as intended, but it doesn't display anything on screen.
I thought I might be missing the link between the ContextMenuStrip and the component it attaches to so I had a look at how the code is auto generated in the design view... however I have no access to the "Controls" object to do Control.Add(this.whatever) and it appears not to be part of the using System... collection.
I have left my testing for this commented out below.
The SuspendLayout and ResumeLayout methods are another thing I looked into after reading that you should call them before and after making changes to UI components. I am not sure if I am correctly using them as they appeared to do nothing, I'm unsure when they are actually required to be used.
Would appreciate being pointed towards what ever I have missed out on, thanks :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
namespace Context
{
class PopulateMenu
{
private void PopulateSubMenu(string fileName, ContextMenuStrip parent, EventHandler onClickDelete, EventHandler onClickView)
{
try
{
Image delete = Properties.Resources.RO_Mx2_24_delete;
Image view = Properties.Resources.OpenFolder1;
parent.SuspendLayout();
//Parent
ToolStripMenuItem attachedFiles = new ToolStripMenuItem(fileName, Properties.Resources.NewDocumentHS);
//Kids
attachedFiles.DropDownItems.Add(new ToolStripMenuItem("View File", view, onClickView));
//if (!hotfolder)
//{
attachedFiles.DropDownItems.Add(new ToolStripMenuItem("Delete File", delete, onClickDelete));
//}
//else
//{
// attachedFiles.DropDownItems.Add(new ToolStripMenuItem("Remove File", delete, onClickDelete));
//}
// Attach kid to parent
parent.Items.Add(attachedFiles);
parent.ResumeLayout();
}
catch { Exception e; }
}
private void BuildHotMenu(List<FileInfo> files, ContextMenuStrip parent)
{
try
{
parent.SuspendLayout();
parent.Items.Add(new ToolStripMenuItem("Hot Folder Files"));
parent.Items.Add(new ToolStripSeparator());
foreach (FileInfo fileInfo in files)
{
PopulateSubMenu(fileInfo.Name, parent, null, null);
}
parent.ResumeLayout();
}
catch { Exception e; }
}
private void BuildDropMenu(List<FileInfo> files, ContextMenuStrip parent)
{
try
{
parent.SuspendLayout();
parent.Items.Add(new ToolStripMenuItem("Dropped Files"));
parent.Items.Add(new ToolStripSeparator());
foreach (FileInfo fileInfo in files)
{
PopulateSubMenu(fileInfo.Name, parent, null, null);
}
parent.ResumeLayout();
}
catch { Exception e; }
}
public void SummonContextMenu()
{
try
{
ContextMenuStrip attachedFilesWithMenu = new ContextMenuStrip();
////ContextMenu
//attachedFilesWithMenu.Name = "attachFilesWithMenu";
//attachedFilesWithMenu.Size = new Size(61, 4);
//ToolStrip ToolStrip1 = new ToolStrip();
////ToolStrip
//toolStrip1.ContextMenuStrip = attachedFilesWithMenu;
//toolStrip1.Location = new Point(0, 0);
//toolStrip1.Size = new Size(284, 25);
//toolStrip1.Name = "toolStrip1";
//toolStrip1.Text = "toolStrip1";
//// Form2
////
//AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
//AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
//ClientSize = new System.Drawing.Size(284, 262);
//Controls.Add(this.toolStrip1);
//ResumeLayout(false);
//PerformLayout();
//static directory for testing only
ConfigurationInformation configurationInformation = new ConfigurationInformation();
configurationInformation.HotFolderPath = "C:\\Users\\alexh\\HotFolder\\";
//Store DirectoryInfo
DirectoryInfo dirInfo = new DirectoryInfo(Environment.ExpandEnvironmentVariables(configurationInformation.HotFolderPath));
//Create list to store file details
List<FileInfo> hotFiles = new List<FileInfo>();
foreach (FileInfo fileInfo in dirInfo.GetFiles())
{
hotFiles.Add(fileInfo);
}
BuildHotMenu(hotFiles, attachedFilesWithMenu);
BuildDropMenu(hotFiles, attachedFilesWithMenu);
}
catch { Exception e; }
}
public PopulateMenu()
{
}
//private System.Windows.Forms.ToolStrip toolStrip1;
//private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
}
}
Well that was actually quite simple. You just have to do it from a Form.
//this.Literally = theAnswer;
this.ContextMenuStrip = myContextMenu;