My for statement isn't working properly - c#

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

Related

C# get folderpath from TreeListNode in treeList devexpress

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).

C# access to TreeNode parameter

Here is code:
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name + " (" + DirSize(new DirectoryInfo(directoryInfo.FullName)) + " bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length + " files)"+ directoryInfo.CreationTime);
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name + " (" + file.Length + " bytes)"));
return directoryNode;
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string selectedNodeText = "a";
textBox1.Text = selectedNodeText;
}
I need to access directoryInfo.CreationTime from TreeNode and display it in treeView1_AfterSelect text.Box1 but I can't find right way.
You can use the Tag property of TreeNode to put the value there and then access it in the event :
directoryNode.Tag = directoryInfo;
and then in event you can access it :
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var directoryInfo = e.Node.Tag as DirectoryInfo;
var time = directoryinfo.CreationTime;
}
or:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var directoryInfo = treeView1.SelectedNode.Tag as DirectoryInfo;
var creationTime = drInfo.CreationTime;
}
Hope it helps!
Tree nodes expose the Tag property that is used to store and retrieve a custom information under nodes. It can even hold a reference to a complex structure.
https://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.tag(v=vs.110).aspx

Copying Files to directory from Multiline Textbox

I am trying to write a C# program that will allow me to select a file and copy that file to a list of directories.
I've written the code to copy the file over and it works, the problem I am having to getting it to copy the file to each line of the textbox, as each line is a different directory.
This is what I have so far:
private void button3_Click(object sender, EventArgs e)
{
int line = 1;
string FileToCopy = listBox3.GetItemText(listBox3.SelectedItem);
if (File.Exists(FileToCopy + #"\user.ini"))
{
File.Copy(FileToCopy + #"\user.ini", textBox1.Lines[line - 1] + #"\user.ini", true);
line++;
label5.Text = "Environment Updated";
}
else
{
label5.Text = "File of Path not Found";
}
}
I'm pretty sure there is a simple solution to this but my searches haven't brought up anything yet. I'm still quite new to C# and programming in general, any help would be appreciated.
Assuming textbox has text
Path1
Path2
Path3
.....
PathN
Then split the text into lines
var lines = textBox1.Text.Split(new string[]{Environment.NewLine}, System.StringSplitOptions.RemoveEmptyEntries);
And then for each line copy the file over.
foreach(var path in lines) {
File.Copy(FileToCopy + #"\user.ini", path + #"\user.ini", true);
}

C# - Open .RPD file (XML file in disguise), Save out as .XML and then open XML in XmlDocument

As the header says - I am trying to Open a .RPD file (which is a XML file in disguise), Save out as .XML and then open XML using XmlDocument to process . . . all in c#.
This code below works until it hits the line string jN = jobName.InnerText; line.
The error I get is:-
System.NullReferenceException: Object reference not set to an instance of an object. at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in XML Display.cs:line 73
Looks to me like it isn't picking up the new XML file correctly - even though it is there?
Can anybody point me in the right direction to get this to work?
// XML reading, writing and pulling out data.
using System;
using System.Windows.Forms;
using System.Xml;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// set up some variables to use
public string document;
public string material;
public string thickness;
public string sheetx;
public string sheety;
public string used;
public Form1()
{
InitializeComponent();
}
public void label1_Click(object sender, EventArgs e) { }
private void Form1_Load(object sender, EventArgs e) { }
private void outputBox_TextChanged(object sender, EventArgs e) { }
public void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
// Filter for xml files only
fDialog.Filter = "RPD File|*.rpd";
// Filter for starting directory - in this case a network drive.
fDialog.Title = "Please pick your RPD file . . .";
if (fDialog.ShowDialog() == DialogResult.OK)
{
outputBox.AppendText("Converting your RPD into an XML, saving and then loading back in!" + System.Environment.NewLine);
// set up xml document - using the filename used - load the XML
XmlDocument thisOrder1 = new XmlDocument();
string fN = fDialog.FileName;
thisOrder1.Load(fN);
int fileExtPos = fN.LastIndexOf(".");
string nFN = fN.Substring(0, fileExtPos)+".xml";
// make a duplicate of the file - rename it to a XML file
System.IO.File.Copy(fN, nFN, true);
XmlDocument thisOrder = new XmlDocument();
// load up the new XML file.
thisOrder.Load(nFN);
outputBox.AppendText("Done!" + System.Environment.NewLine);
// try and process this file
try
{
// pull in node list
XmlNodeList xmlnode = thisOrder.GetElementsByTagName("Sheet");
XmlNode jobName = thisOrder.DocumentElement.SelectSingleNode("JobName");
// pull jobName in from the XML
string jN = jobName.InnerText;
// replace question marks and extra spaces with nothing
jN = jN.Replace("?", "");
jN = jN.TrimEnd();
// outout the Job Name
outputBox.AppendText("Job Name > " + jN + System.Environment.NewLine);
// find the CR number from - this will have to be updated.
XmlNode crNumber = thisOrder.DocumentElement.SelectSingleNode("RadanSchedule/JobDetails/NestFolder");
string cR = crNumber.InnerText;
cR = cR.Substring(45, 8);
// output CR number and setup ready to show Material and amount used
outputBox.AppendText("CR Number > " + cR + System.Environment.NewLine + System.Environment.NewLine);
outputBox.AppendText("Material\t\t\t\tUsed" + System.Environment.NewLine);
// main routine to pull out data as needed.
try
{
for (int i = 1; i < xmlnode.Count; i++)
{
used = string.Format(xmlnode[i].ChildNodes.Item(11).InnerText);
if (Convert.ToInt32(used) >= 1)
{
material = string.Format(xmlnode[i].ChildNodes.Item(2).InnerText);
thickness = string.Format(xmlnode[i].ChildNodes.Item(3).InnerText);
sheetx = string.Format(xmlnode[i].ChildNodes.Item(5).InnerText);
sheety = string.Format(xmlnode[i].ChildNodes.Item(6).InnerText);
outputBox.AppendText(material + "-" + thickness + "-" + sheetx + "-" + sheety + "\t\t\t" + used + System.Environment.NewLine);
}
}
}
catch
{
// if the data is found to be empty - tell us
outputBox.AppendText("No data found!" + System.Environment.NewLine);
}
}
catch (Exception ex)
{
// if there is a major problem - tell us
outputBox.AppendText("Problem processing new XML file!" + System.Environment.NewLine + "ERROR > " + ex + System.Environment.NewLine);
}
}
}
}
}
Edited the code above to show ALL code.
Thank you.

How do I save some files under a directory in a new directory after making some changes

I opened a directory and I read some files in that directory amd made some changes, now I want to save the changes with the same file names at F:\BI\Out\ and keep the original files.
when I added these two lines
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
I was able to save the files under the new folder\Out,
but when I opened them I found that only one file is changed correctly and all the other files the old words are replace by blank space not by the new words.
Can anyone help me Thanks
string text = "";
string[] files;
private void Form1_Load(object sender, EventArgs e)
{
try
{
files = Directory.GetFiles(#"F:\BI\In\", "*.*", SearchOption.AllDirectories);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEtlPath.Text == "")
{
MessageBox.Show("Please Enter path");
txtEtlPath.Focus();
}
else
{
foreach (string file in files)
{
if (System.IO.File.Exists(file))
{
text = File.ReadAllText(file);
text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI");
text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW");
text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim());
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
}
Within your foreach () loop:
If you want the subfolder structure of the files found, do a replace on the filepath:
var outFilePath = file.Replace(#"F:\BI\In\", #"F:\BI\Out\");
You will need to create the subfolder before you can write the changed file:
new FileInfo(outFilePath)).Directory.Create();
If you don't want the subfolders, you can write directly into the top folder:
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
Writing is simple, just keep in mind there is an optional encoding parameter:
File.WriteAllText(outFilePath, text);

Categories