Get files in directory with multiple search patterns - c#

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

Related

How do I list the file in it by increasing the filename by one?

I have thousands of project folders and inside each folder I have another folder named test. There is only one pdf file in this folder. When I select the top folder, I want to get the pdfs in these folders and copy them to another location. How can I select these pdfs?
There are other pdfs under the Project Folders, I only want the pdfs in the test folder.
My folder names are increasing one by one(Project1,Project2,3,4,5,6,7.....)
My Project
 ↳-Project1
     ↳Test
        ↳Project1.pdf
 ↳-Project2
     ↳Test
        ↳Project2.pdf
 ↳-Project3
     ↳Test
        ↳Project2.pdf
I want to something just like this
The image belongs to me. Currently it only lists all pdfs in selected folders. I couldn't filter pdf files. I am using FolderBrowserDialog for select the folder
private string[] dirs;
private string[] files;
private System.IO.FileInfo file;
private void GetPDF(string path, ref List<string> listPDF)
{
try
{
dirs = System.IO.Directory.GetDirectories(path);
foreach (string item in dirs)
{
GetPDF(item, ref listPDF);
}
files = System.IO.Directory.GetFiles(path);
foreach (string item in files)
{
file = new System.IO.FileInfo(item);
if (file.DirectoryName.ToLower().EndsWith("test") && file.Extension.ToLower() == ".pdf")
{
listPDF.Add(file.FullName);
}
}
}
catch (Exception)
{
throw;
}
}
private void Function1()
{
try
{
System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
List<string> listPDF = new List<string>();
GetPDF(dialog.SelectedPath, ref listPDF);
listPDF.Sort();
foreach(string filePath in listPDF)
{
Console.WriteLine(filePath);
}
}
}
catch (Exception)
{
throw;
}
}

How do I get the index of a node by value

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

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

File not found error from the listbox C# win forms

I have a listbox and it has some files loaded from a directory folder.
Code to load the files into the listBox1:
private void Form1_Load(object sender, EventArgs e)
{
PopulateListBox(listbox1, #"C:\TestLoadFiles", "*.rtld");
}
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file.Name);
}
}
I want to read and display the attributes values to the labels in the form. The loaded files in the listBox1, here is the code:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string path = (string)listBox1.SelectedItem;
DisplayFile(path);
}
private void DisplayFile(string path)
{
string xmldoc = File.ReadAllText(path);
using (XmlReader reader = XmlReader.Create(xmldoc))
{
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "description":
if (!string.IsNullOrEmpty(reader.Value))
label5.Text = reader.Value; // your label name
break;
case "sourceId":
if (!string.IsNullOrEmpty(reader.Value))
label6.Text = reader.Value; // your label name
break;
// ... continue for each label
}
}
}
}
Problem:When I click on the file in the listBox1 after the form is loaded,the files are loaded from the folder into the listbox but it's throwing an error File not found in the directory.
How can I fix this problem???
That is because you are adding File.Name instead you should add File.FullName in your listbox
lsb.Items.Add(file.FullName);
so your method PopulateListBox should become:
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file.FullName);
}
}
EDIT:
It looks like you want to display only the file name, not the full path. You could follow a following approach. In PopulateListBox, add file instead of file.FullName so the line should be
foreach (FileInfo file in Files)
{
lsb.Items.Add(file);
}
Then in SelectedIndexChanged event do the following:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FileInfo file = (FileInfo)listbox1.SelectedItem;
DisplayFile(file.FullName);
}
This should get you the full name (file name with path) and will resolve your exception of File Not Found
The problem you are facing is that in the listbox you only specify the file name, and not the entire file path and name, so when it looks for the file you it cant find it.
From FileInfo.Name Property
Gets the name of the file.
Whereas File.ReadAllText Method (String) takes path as a parameter.
You are not specifying the full path.
Try something like this:
DisplayFile(#"C:\TestLoadFiles\" + path)

Categories