How do I get the index of a node by value - c#

So I was making a code editor (It is a fusion between Visual Studio Code and the Python IDLE) in C# WFA (Windows Form Application). I was making the project explorer where I faced many issues, mainly being:
I have found the solution get the files displayed under the sub-directories but if I use the way I am using to add files into the main directory, it will add all the files of all sub-directories in one sub-directory. I found out that the solution to this is that I get the index of the node by using it's value. I googled some properties of Nodes and the tree view but I couldn't find a function to do so. So Like any ideas on How I add the files of the specific subdirectory under that directory only?
Code:
My ProjectBase:
public ProjectBase()
{
InitializeComponent();
menuStrip1.Renderer = new myRenderer();
label1.Text = ProjectCreation.ProjectName;
string FolderPath = ProjectCreation.rootDir;
string[] fileArray = Directory.GetFiles(FolderPath);
string[] folderArray = Directory.GetDirectories(FolderPath);
treeView1.BeginUpdate();
treeView1.Nodes.Clear();
treeView1.Nodes.Add(FolderPath);
foreach (string folder_name in folderArray)
{
treeView1.Nodes[0].Nodes.Add(folder_name);
string[] fileArrray2 = Directory.GetFiles(folder_name);
foreach (string file_name2 in fileArrray2)
{
}
}
foreach (string file_name in fileArray)
{
treeView1.Nodes[0].Nodes.Add(file_name);
}
}
Choose Path for Project Creatiion (I use this area to get the rootDir or the working directory)
dlg = new CommonOpenFileDialog();
dlg.Title = "Project Creation Path";
dlg.IsFolderPicker = true;
if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
{
folder = dlg.FileName;
rootDir = Functions.GetLastPathSegment(folder);
}
My Project Manger Open Project Code:
private void button1_Click(object sender, EventArgs e)
{
ProjectCreation.dlg = new CommonOpenFileDialog();
ProjectCreation.dlg.Title = "Open New Project";
ProjectCreation.dlg.IsFolderPicker = true;
if (ProjectCreation.dlg.ShowDialog() == CommonFileDialogResult.Ok)
{
ProjectCreation.folder = ProjectCreation.dlg.FileName;
ProjectCreation.rootDir = Functions.GetLastPathSegment(ProjectCreation.folder);
ProjectBase project_new = new ProjectBase();
project_new.Show();
this.Hide();
}
}

Related

How can I open a specific file with this in c#?

I have a form that has a list and a button. When you press the button, I want it to write the contents of a specific file(scores.txt) in the list.
This is my code now but with this I can choose the file, but it doesn't open it automatically:
private void btnOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents(*.txt)|*.txt", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog()==DialogResult.OK)
{
string[] lines = System.IO.File.ReadAllLines(ofd.FileName);
List<string> list = new List<string>();
foreach (string s in lines)
{
list.Add(Convert.ToString(s));
listReadFile.Items.Add(s);
}
}
}
}
Just hard code the filename.
string fileName = #"c:\data\score.txt";
enter code here
string[] lines = System.IO.File.ReadAllLines(fileName);
List<string> list = new List<string>();
foreach (string s in lines)
{
list.Add(Convert.ToString(s));
listReadFile.Items.Add(s);
}
That'll be because you're using an OpenFileDialog.
If you want it to open a file automatically, replace ofd.FileName with the path string of the file you want it to open.
As a side note, I recommend adding this string into your application config, instead of hard-coding it directly.

Get files in directory with multiple search patterns

I have a method that gets files in specified directory with extension txt. Besides those files, I want to also get files with extensions ppt, docx etc. How to achieve that?
this is my current code:
private void button2_Click(object sender, EventArgs e){
listView1.Items.Clear();
if (textBox1.Text != ""){
List<string> files = new List<string>();
files = Directory.GetFiles(textBox1.Text, "*.txt,*.ppt").ToList();
progressBar1.Maximum = files.Count;
progressBar1.Value = 0;
ListViewItem it;
foreach (var file in files){
it = new ListViewItem(file.ToString());
it.SubItems.Add(System.IO.Path.GetFileName(file.ToString()));
it.SubItems.Add(System.IO.Path.GetExtension(file.ToString()));
listView1.Items.Add(it);
progressBar1.Increment(1);
}
} else
MessageBox.Show("Select directory first");
}
Your question is not clear but which i understand you want to get files with different extension from a specified path. We can't do this using Directory.GetFiles("c://etc.", "*.txt") because it works on a single search pattern. You can use this,
string[] Extensions = {"*.txt", "*.doc", "*.ppt"};
foreach(var ext in Extensions)
{
GetFiles(ext);
}
private void GetFiles(string ext)
{
List<string> files = new List<string>();
files = Directory.GetFiles("c:/something", ext).ToList();
// Something you want to do with these files.
}
files = Directory.GetFiles(#textBox1.Text, "*.txt").ToList();
files.AddRange(Directory.GetFiles(#textBox1.Text, "*.docx").ToList());
files.AddRange(Directory.GetFiles(#textBox1.Text, "*.ppt").ToList());
also, you should consider checking for validity of path from textBox1, something like this:
if (!Directory.Exists(#textBox1.Text))
{
MessageBox.Show("invalid folder");
return;
}

How to save content from List<string> to a text file in C#?

I have a listbox that displays the names of the files that are opened either with a dragDrop functionality or with an OpenFileDialog, the file paths are stored in the List named playlist, and the listbox only displays the names without paths and extensions. When my form closes, the playlist content is saved to a .txt file. When I open again my application, the content in the text file is stored again in the listbox and the playlist. But when I add new files after re-opening the form, I don't know why it leaves a blank line between the last files and the recently added ones.
This is the code I use to WRITE the content of playlist(List) in the txt file:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(listBox1.Items.Count > 0)
{
StreamWriter str = new StreamWriter(Application.StartupPath + "/Text.txt");
foreach (String s in playlist)
{
str.WriteLine(s);
}
str.Close();
}
This is the code used to READ the same txt file:
private void Form1_Load(object sender, EventArgs e) //Form Load!!!
{
FileInfo info = new FileInfo(Application.StartupPath + "/Text.txt");
if(info.Exists)
{
if (info.Length > 0)
{
System.IO.StreamReader reader = new System.IO.StreamReader(Application.StartupPath + "/Text.txt"); //StreamREADER
try
{
do
{
string currentRead = reader.ReadLine();
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
} while (true);
}
catch (Exception)
{
reader.Close();
listBox1.SelectedIndex = 0;
}
}
else
{
File.Delete(Application.StartupPath + "/Text.txt");
}
}
else
{
return;
}
}
The code used to add files to listbox and playlist:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select File(s)";
ofd.Filter = "Audio Files (*.mp3, *.wav, *.wma)|*.mp3|*.wav|*.wma";
ofd.InitialDirectory = "C:/";
ofd.RestoreDirectory = false;
ofd.Multiselect = true;
ofd.ShowDialog();
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(s));
playlist.Add(s);
}
listBox1.SelectedIndex = 0;
This is what I get when I add new files after re-opening my form:
Thanks in advance, I hope StackOverflow community can help me!
First of all: debug your code and you'll find the problem yourself :)
Issue is the use of the WriteLine method. The last line you write should use the Write method instead so that you don't have an empty line at the end. Alternatively and easier to implement is to only add non-empty lines to your playlist such like this:
// ...
do
{
string currentRead = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(currentRead)) // ignore empty lines
{
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
}
} while (true);
As a side comment: while (true) and using exception handling is a bad approach to end a loop.

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

How to get file path from OpenFileDialog and FolderBrowserDialog?

Hey there i started learning C# a few days ago and I'm trying to make a program that copies and pastes files (and replaces if needed) to a selected directory but I don't know how to get the directory and file paths from the openfiledialog and folderbrowserdialog
what am I doing wrong?
Here's the code:
namespace filereplacer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();
if (directchoosedlg.ShowDialog() == DialogResult.OK)
{
folderPath = directchoosedlg.SelectedPath;
}
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
choofdlog.ShowDialog();
}
private void replacebtn_Click(object sender, EventArgs e)
{
// This is where i'm having trouble
}
public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace)
{
File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false);
}
}
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder and selected file name you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).
In that case you could get all selected files in string[]:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);
you can store the Path into string variable like
string s = choofdlog.FileName;
To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.
var file = choofdlog.FileName; // for one file
or for multiple files
var files = choofdlog.FileNames; // for multiple files.
To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path
Create this class as Extension:
public static class Extensiones
{
public static string FolderName(this OpenFileDialog ofd)
{
string resp = "";
resp = ofd.FileName.Substring(0, 3);
var final = ofd.FileName.Substring(3);
var info = final.Split('\\');
for (int i = 0; i < info.Length - 1; i++)
{
resp += info[i] + "\\";
}
return resp;
}
}
Then, you could use in this way:
//ofdSource is an OpenFileDialog
if (ofdSource.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(ofdSource.FolderName());
}
Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.
A primitive quick fix that works.
If you only use OpenFileDialog, you can capture the FileName, SafeFileName, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
I am sorry if i am late to reply here but i just thought i should throw in a much simpler solution for the OpenDialog.
OpenDialog ofd = new OpenDialog();
var fullPathIncludingFileName = ofd.Filename; //returns the full path including the filename
var fullPathExcludingFileName = ofd.Filename.Replace(ofd.SafeFileName, "");//will remove the filename from the full path
I have not yet used a FolderBrowserDialog before so i will trust my fellow coders's take on this. I hope this helps.
String fn = openFileDialog1.SafeFileName;
String path = openFileDialog1.FileName.ToString().Replace(fn, "");

Categories