I created a File Searcher ( I provide the directory of folders in Open Directory button and i choose Extension if (txt or png or html etc...) and in term i write the word i want to search for it like
Example.txt
index.html,
etc...
and after that I click Search For Files and I get Result In the listBox1
After that to Search for a specific word I write in Term The Word To Search it inside a selected txt file from the listbox1 but for txt Files I want to Search a specific Word in all txt files without selecting any file from listbox1 and I want a code to show how many files I get in the result (listbox1) in number and how to open a specific file from listbox1 just with clicking it 2 times and how to copy a file or select or remove from listbox1
Questions :
how to change the code of this (Search For Word In Specific File) in a code that can (Search For Word In All Files And Give me Results)?
How to open file that is shown in the listbox?
How to copy file inside the file in the listbox?
How to copy a file or select or remove from listbox1 ?
How to open a specific file from listbox1 just with clicking it 2 times ?
What is the code to show how many files i get in the result (listbox1) in number ?
The Code :
private void FileFound(string path)
{
listBox1.BeginInvoke((Action)delegate ()
{
listBox1.Items.Add(path);
});
}
private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs args)
{
MessageBox.Show("Done");
}
private void WorkInBackground(object sender, DoWorkEventArgs args)
{
searcher.Search();
}
private void button1_Click(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex == -1 || string.IsNullOrEmpty(textBox1.Text)|| string.IsNullOrEmpty(textBox2.Text) )
{
MessageBox.Show("Please Select An Extension Or Select A Directory Or Fill a word");
return;
}
listBox1.Items.Clear();
this.searcher.Term = textBox2.Text;
this.searcher.Dir = textBox1.Text;
this.searcher.Ext = comboBox1.SelectedItem.ToString();
bgWorker.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
dialog.RestoreDirectory = true;
if(dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
textBox1.Text = dialog.FileName;
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
if (!listBox1.SelectedItem.ToString().Contains(".txt") )
{
MessageBox.Show("Please Select Text File");
return;
}
if (string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("Please type a Term");
return;
}
this.searcher.Term = textBox2.Text;
this.searcher.Dir = listBox1.SelectedItem.ToString();
string words = File.ReadAllText(listBox1.SelectedItem.ToString());
if (words.ToLower().Contains(textBox2.Text.ToLower()))
{
MessageBox.Show("word Founded");
}
else
{
MessageBox.Show("No Such a Word");
}
}
catch (Exception)
{
MessageBox.Show("Please Select A File");
}
//bgWorker.RunWorkerAsync();
}
}
Related
I'm trying to write a program that will read a text file with a list of names listed like
Michael Jordan
Kobe Bryant
Larry Bird
Lebron James
I've written the code to open the file and rewrite the file and included it.
Once Loaded how can I sort this list by Last Name and then by First name?
List<string> cstrName = new List<string>();
private void Sorter_Load(object sender, EventArgs e)
{
try
{
//Load the array with the data in the file
FileStream nameFile = new FileStream("input.txt",FileMode.Open);
StreamReader nameStreamReader = new StreamReader(nameFile);
while (nameStreamReader.Peek() != -1)
{
cstrName.Add(nameStreamReader.ReadLine());
}//End Loop
nameFile.Close(); //Close file
}
//Sets an error message if there is an issue opening the file
catch (Exception ex)
{
MessageBox.Show("Error Opening File. Data not loaded " +
ex.Message,"File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void btnSortByName_Click(object sender, EventArgs e)
{
{
cstrName.Sort();
}
//display names in a list box
displayNames();
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.File.WriteAllLines("input2.txt", cstrName);
this.Close();
}
Swap your cstrName.Sort(); for
cstrName = cstrName.OrderBy(x => x.Split(' ').Last()).ToList();
Make sure you have Using System.Linq; at the top of your file.
It orders cstrName by the last word in the string (working out words by splitting the string by spaces ' ').
I am new to C#. I am working on a Windows Form that should do the following:
Browse files on local drive
Allow the user to select files
List the selected files in a listBox
Allow the user to input a new file name and, when they click the rename button, it renames the selected file in the ListBox.
I am not able to do step 4 as the new text is changed in the listBox but the actual file name is still the same in folder. How can I do that? I have listed below the Form.cs
Thank you.
public partial class everSupportForm : Form
{
private void buttonSelect_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
var myDialog = new OpenFileDialog();
myDialog.InitialDirectory = #"c:\";
myDialog.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
// + "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" //If you want to add filters for browsing only images.
myDialog.FilterIndex = 1;
myDialog.RestoreDirectory = true;
myDialog.Multiselect = true;
myDialog.Title = "Please Select File(s) to Rename";
if (myDialog.ShowDialog() != DialogResult.OK) return;
{
foreach (var file in myDialog.FileNames)
{
try
{
if ((myStream = myDialog.OpenFile()) != null)
{
using (myStream)
{
outputListBox.Items.Add(System.IO.Path.GetFileName(file));
}
}
}
catch (Exception ex)
{
// Could not load File specifying the causes
MessageBox.Show("Cannot display the File");
}
}
}
}
private void buttonExit_Click(object sender, EventArgs e) => Application.Exit();
// Removes a selected item
private void buttonRemove_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >= 0)
outputListBox.Items.RemoveAt(outputListBox.SelectedIndex);
}
// Clears the listed images ListBox
private void buttonClear_Click(object sender, EventArgs e) => outputListBox.Items.Clear();
private void buttonRename_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >= 0)
outputListBox.Items[outputListBox.SelectedIndex] = newNametextBox.Text;
else MessageBox.Show("There is no Files in the Above list to be Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
First of all, you have a problem here.
You're adding the files names using Path.GetFileName, so you won't have the files paths anymore => you can't rename them.
Solution 1 - Adding the paths to the listbox
You simple remove the Path.GetFileName and in when the rename button is clicked, you use an InputBox to ask the user for the new file name:
N.B: Add a reference to Microsoft.VisualBasic, InputBoxis in the Microsoft.VisualBasic.Interaction namespace.
private void buttonRename_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >=0)
{
string fileToRename = outputListBox.Items[outputListBox.SelectedIndex].ToString();
string newFileName = InputBox("Please enter the new file's name:", "Rename file", "Default value");
if (!string.IsNullOrEmpty(newFileName))
{
string fileName = Path.GetFileName(fileToRename);
string newFilePath = fileToRename.Replace(fileName, newFileName);
System.IO.File.Move(fileToRename, newFilePath);
outputListBox.Items[outputListBox.SelectedIndex] = newFilePath;
}
}
else
{
MessageBox.Show("There is no Files in the Above list to be Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Solution 2 -- Keep a seperate list containing the paths
The concept is the same as the first solution, but instead of adding the file paths to your listbox, you add the file names but you keep a seperate list of paths that is synced with your listbox.
Meaning that, if you modify the listbox, modify the list of paths.
After that you can access the file paths using the listbox's SelectedIndex (since they are synced).
Currently, I have a browser dialog that opens and allows the user to select a folder in which doc / docx files will be merged into one file. At the moment, it is rigged up to merge files once the 'DialogResult.ok' button is dismissed in the browser dialog. as shown below:
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"C:\";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
}
private void combineButton_Click(object sender, EventArgs e)
{
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + AllDocFolder.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
the issue i am having is that i want the 'combineButton' to merge the documents as opposed to the 'DialogResult.ok'. When i copy the lines:
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
into the combineButton area, i get an error saying 'the name 'selectedFolder' does not exist in the current context'. This may be a stupid question, but is there a quick way to remedy this?
As far as I understand your problem, you want to split the folder selection and the merging of the documents, right?
So you could put the information about the target directory into a class variable:
public class MyForm
{
private string[] _sourceFiles;
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"C:\";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
_sourceFiles = Directory.GetFiles(selectedFolder, "*.doc");
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (_sourceFiles != null && _sourceFiles.Length > 0)
{
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(_sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + _sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
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);
I am trying to set the selected folder in a FolderBrowserDialog control as a variable, so I can use it within another method
The code I have so far is:
private void button18_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// We print the number of files found.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
So I could call the selected folder in the control above in a method like this:
Process.Start("test.exe", <Folder Selection Here> );
I started looking at this before I noticed that you had requested the question to be closed. Anyway here's the code should it be useful for someone else.
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
//Choose the default start up folder
string selectedFolder = #"C:\Dev";
//Set that into the dialog
folderBrowserDialog1.SelectedPath = selectedFolder;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
//Grab the folder that was chosen
selectedFolder = folderBrowserDialog1.SelectedPath;
// The user selected a folder and pressed the OK button.
// We print the number of files found.
string[] files = Directory.GetFiles(selectedFolder);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
MessageBox.Show(selectedFolder);
}
}