C# get folderpath from TreeListNode in treeList devexpress - c#

I use XtratreeList with fileExplorerAssistant. I have a problem when I want to get the path of the selected folder from treelist. Or I have a problem in getting the folder path from TreeListNode. Please help me.
My code is :
private void frmMovieAddAuto_Load(object sender, EventArgs e)
{
// Scan for all partitions
System.IO.DriveInfo[] driveList = System.IO.DriveInfo.GetDrives();
foreach (var drive in driveList)
{
// Select only logical fixed partitions
if (drive.DriveType == System.IO.DriveType.Fixed && drive.IsReady)
{
// Add each drive as a root node
treeListExtension1.RootNodes.Add(new PathNode(drive.RootDirectory.ToString()));
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
TreeListColumn columnname;
columnname = treeList1.Columns[0];
columnname.Caption = "Folder Name";
List<TreeListNode> nodes = treeList1.GetNodeList();
foreach (TreeListNode node in nodes)
{
if (node.Checked == true)
{
DirectoryInfo di = new DirectoryInfo(node.GetValue(columnname).ToString());
foreach (FileInfo fi in di.GetFiles("*.avi;*.mpg;*.mpeg;*.mp4;*.mkv;*.divx;*.AVI;*.MPG;*.MPEG;*.MP4;*.MKV;*.DIVX", SearchOption.AllDirectories))
{
//do something
}
}
}
}

In this code:
private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
// Get the node that is currently focused (selected) in the TreeList
TreeListNode focusedNode = treeList1.FocusedNode;
// Get the column that contains the folder path
TreeListColumn folderPathColumn = treeList1.Columns[0];
// Get the value of the folder path column from the focused node
string folderPath = focusedNode.GetValue(folderPathColumn).ToString();
if(focusedNode.Checked == true)
{
pathfolderList.Add(folderPath);
}
}
In this line code:
string folderPath = focusedNode.GetValue(folderPathColumn).ToString();
It gives this error:
'Object reference not set to an instance of an object.'

Your question is how to get the full path of a DevExpress.XtraTreeList.Nodes.TreeListNode. This requires traversing the DisplayText from the selected node up to its root, When this collection is reversed and combined, the result is the full path.
foreach (var node in treeList1.GetNodeList())
{
List<string> builder = new List<string>();
TreeListNode traverse = node;
// This adds the display text from the leaf to the root.
while(traverse != null)
{
builder.Add(traverse.GetDisplayText(0));
traverse = traverse.ParentNode;
}
// What we want is the root to the leaf, so reverse the list.
builder.Reverse();
// Now combine into a path.
var path = Path.Combine(builder.ToArray());
Debug.WriteLine(path);
}
You might also find the DevExpress documentation helpful (their approach is slightly different).

Related

Get and return filepath by foreach

I want to make a program to able to save every file path which the user selected.
after that do some prosses for each file. for example, convert video file one by one.
Could you tell me why foreach does not work?
private void btnInput_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialogInput = new OpenFileDialog();
openFileDialogInput.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
openFileDialogInput.Filter = "Video Files|*.mp4|TS Files|*.ts";
openFileDialogInput.Multiselect = true;
openFileDialogInput.FilterIndex = 1;
DialogResult result = openFileDialogInput.ShowDialog();
string [] inputPath = openFileDialogInput.FileNames;
foreach (var item in inputPath)
{
item;
}
}
inputPath gets all file paths that the user selected. but I don't know how can I get them, one by one and make some prosses on them.
You Can try this:
private void AddWatermark(string videoFilePath)
{
// Add your logic here to add watermark
}
And in the foreach loop:
foreach (var item in inputPath)
{
AddWatermark(item);
}

Show file names in listbox for selected directory in treeview

I have a button "Choose folder". When i choose folder, it shows all the directories and sub-directories in treeview. Everything is working fine.
What i need now is - when i click in the treeview on some directory in shows all files that is in that directory in the listbox.
private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
DirectoryInfo directoryInfo = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
if (directoryInfo.Exists)
{
VeidotKoku(directoryInfo, treeView1.Nodes);
}
}
}
private void VeidotKoku(DirectoryInfo directoryInfo, TreeNodeCollection Pievienot)
{
TreeNode tagadejaNode = Pievienot.Add(directoryInfo.Name);
foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
{
VeidotKoku(subdir, tagadejaNode.Nodes);
}
}
System.IO.Path.GetFileNameWithoutExtension(fileLocationPath);
Will get the extensionless path.
Else, if you just want to get the value you can split the path and get the last element.
foreach(string filePath in filePaths)
{
string[] brokenPath = filePath.Split('/');
listBox.Add(brokenPath.Last());
}
Top of my head.

How search a file by its name and open it? [duplicate]

This question already has an answer here:
How to open a pdf file in a WebForm application by search?
(1 answer)
Closed 7 years ago.
Currently i'm doing a web application project in ASP.net C#.
Here i have a problem to search a file by its name. Below code is shows were i did, but the problem is, it does not shows the file according to the search name, since it show all file name in directories.
Another problem is, i don't how to open the search files. Can any one help me?
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
string[] pdffiles = Directory.GetFiles(#
"\\192.168.5.10\\fbar\\REPORT\\CLOTHO\\H2\\REPORT\\", "*.pdf", SearchOption.AllDirectories);
string search = TextBox1.Text;
ListBox1.Items.Clear();
foreach(string file in pdffiles)
{
ListBox1.Items.Add(Path.GetFileName(file));
}
TextBox1.Focus();
} else
{
Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
}
}
First you have to use your search variable to filter out intended files
protected void Button1_Click(object sender, EventArgs e)
{
string search = TextBox1.Text;
if (TextBox1.Text != "")
{
string[] pdffiles = Directory.GetFiles(#"\\192.168.5.10\\fbar\\REPORT\\CLOTHO\\H2\\REPORT\\", string.Format("*{0}*.pdf",search), SearchOption.AllDirectories);
ListBox1.Items.Clear();
foreach (string file in pdffiles)
{
ListBox1.Items.Add(Path.GetFileName(file));
}
TextBox1.Focus();
}
else
{
Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
}
}
Now to open selected file.
protectecd void ListBox1_SelectedIndexChanged(object sender,EventArgs e)
{
string fileName= ListBox1.SelectedItem.ToString();
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition",string.Format("attachment; filename={0}",filename));
Response.TransmitFile(fileName);
Response.End();
}
you need to use your string search to check if file matches it
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
File[] pdffiles = Directory.GetFiles(#"\\192.168.5.10\fbar\REPORT\CLOTHO\H2\REPORT\", "*.pdf", SearchOption.AllDirectories);
string search = TextBox1.Text;
ListBox1.Items.Clear();
foreach (var file in pdffiles)
{
if(file.Name==search)
{
ListBox1.Items.Add(Path.GetFileName(file));
}
}
TextBox1.Focus();
}
else
{
Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
}
}
Also notice you have written the path in GetFiles function
I think the path should be #"\\192.168.5.10\fbar\REPORT\CLOTHO\H2\REPORT\". Also, Directory.EnumerateFiles might be more efficient.
Here's how I would search for any files that CONTAIN the searchName
using System.Linq;
string reportDirectoryName = "..."; // fill in with full path
string searchName = TextBox1.Text;
if (string.IsNullOrWhitespace(searchName))
return ...;
var files = Directory.EnumerateFiles(reportDirectoryName, "*.pdf", SearchOption.AllDirectories);
.Select(n => Path.GetFileName(n))
.Where(n => n.Contains(searchName);
ListBox1.Items.Clear();
ListBox1.Items.Add(files);

My for statement isn't working properly

I have tried so much different iterations of the for loops and all of them dont work properly or work only halfway. So I cant figure it out.
Heres my form:
So what its supposed to do is create a folder for each node in the treeview (Named FolderTV) when I click the Create folders button.
What it currently does is only creates the New_Mod folder and the Data folder nothing else. I want it to create a folder for every node and subnode. For example it would create the New_Mod folder and then within that folder It will create the Data, Models, and Textures folder and within the Data folder it would create a Scripts folder.
Here's my code for that button:
private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i <= FoldersTV.Nodes.Count; i++)
{
FoldersTV.SelectedNode = FoldersTV.TopNode;
MessageBox.Show("Current Node: " + FoldersTV.SelectedNode.Text.ToString());
Directory.CreateDirectory(SEAppdata + "\\" + FoldersTV.SelectedNode.Text.ToString());
for (int x = 0; x <= FoldersTV.Nodes.Count; x++)
{
TreeNode nextNode = FoldersTV.SelectedNode.NextVisibleNode;
MessageBox.Show("Next Node: " + nextNode.Text.ToString());
Directory.CreateDirectory(SEAppdata + "\\" + FoldersTV.SelectedNode.Text.ToString() + "\\" + nextNode.Text.ToString());
x++;
}
i++;
}
}
Try this (untested) recursive solution and try to understand it first ;)
private void CreateDirs(string path, IEnumerable<TreeNode> nodes) {
foreach(var node in nodes) {
// string dir = path + "\\" + node.Text;
string dir = Path.Combine(path, node.Text);
Directory.CreateDirectory(dir);
CreateDirs(dir, node.Nodes);
}
}
private void button3_Click(object sender, EventArgs e) {
CreateDirs(SEAppdata, FoldersTV.Nodes);
}
EDIT: Version with few debug printouts:
// using System.Diagnostics;
private void CreateDirs(string path, IEnumerable<TreeNode> nodes) {
// iterate through each node (use the variable `node`!)
foreach(var node in nodes) {
// combine the path with node.Text
string dir = Path.Combine(path, node.Text);
// create the directory + debug printout
Debug.WriteLine("CreateDirectory({0})", dir);
Directory.CreateDirectory(dir);
// recursion (create sub-dirs for all sub-nodes)
CreateDirs(dir, node.Nodes);
}
}
See: System.Diagnostics.Debug.WriteLine

TreeView Control unexpected event behavior

In the MSDN is writen about TreeNode that:
"By default, a node is in selection mode."
"To put a node into selection mode, set the node's NavigateUrl property to an empty string."
"When a node is in selection mode, use the SelectAction property to specify which event or events are raised when a node is selected."
"Setting TreeNodeSelectAction value TreeNodeSelectAction.Select Raises the SelectedNodeChanged event when a node is selected."
Please see TreeNode
Here is the problem and possibly a bug in the control:
When I set the TreeNode object PopulateOnDemand value to true and call the Collapse() function on that node.
Then the TreeNodeExpanded event is raised in addition to the SelectedNodeChanged event.
This is in complate contradiction to what is writen in the MSDN.
According to the MSDN this sould happen only if TreeNodeSelectAction Property is set to
TreeNodeSelectAction.SelectExpand value.
Does some know whats the cause for that?
Here is the code:
<asp:TreeView ID="TreeView1" runat="server" AutoGenerateDataBindings="False"
onselectednodechanged="TreeView1_SelectedNodeChanged"
ontreenodepopulate="TreeView1_TreeNodePopulate">
</asp:TreeView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string path = Server.MapPath(".");
PopulateTopNodes(path);
}
}
//MSDN : Occurs when a node with its PopulateOnDemand property set to true is expanded in //the TreeView control.
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
LoadChildNode(e.Node);
}
private void PopulateTopNodes(string pathToRootFolder)
{
DirectoryInfo dirInfo = new DirectoryInfo(pathToRootFolder);
DirectoryInfo[] dirs = dirInfo.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
string relativePath = (dir.FullName).Replace(pathToRootFolderPrefix, "");
TreeNode folderNode = new TreeNode(dir.Name, relativePath);
if (dir.GetDirectories().Length > 0)
{
folderNode.PopulateOnDemand = true;
folderNode.Collapse();
}
folderNode.NavigateUrl = "";
folderNode.SelectAction = TreeNodeSelectAction.Select;
TreeView1.Nodes.Add(folderNode);
}
}
private void LoadChildNode(TreeNode treeNode)
{
string d = treeNode.NavigateUrl;
string action = treeNode.SelectAction.ToString();
string fullPath = Path.Combine(pathToRootFolderPrefix, treeNode.Value);
DirectoryInfo dirInfo = new DirectoryInfo(fullPath);
DirectoryInfo[] dirs = dirInfo.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
string relativePath = (dir.FullName).Replace(pathToRootFolderPrefix, "");
TreeNode folderNode = new TreeNode(dir.Name, relativePath);
if(dir.GetDirectories().Length>0){
folderNode.PopulateOnDemand = true;
folderNode.Collapse();
}
folderNode.NavigateUrl = "";
folderNode.SelectAction = TreeNodeSelectAction.Select;
treeNode.ChildNodes.Add(folderNode);
}
}
//MSDN:Occurs when a node is selected in the TreeView control.
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
}
Thanks
I'm don't know ASP.Net, but just reading your code you are setting it to SelectExpand but in your comments above it sounds like you think you're setting it to Select (or this just a typo in the sample code?). In both methods in your sample it's written as:
folderNode.SelectAction = TreeNodeSelectAction.SelectExpand;

Categories