c# with visual studio windows form | How to search a textbox input into a file and return the search - c#

I am a beginner at C# and I am writing a project where I created a method for reading a txt file.
I have a a textbox with a search button. What the program must do is read the input in the textbox, search in the file method and present the matching result in a list box.
I already have some coding like this, but it returns nothing. Can anyone help me?
private void searchButton_Click(object sender, EventArgs e)
{
String[] findValues = this.nameTextBox.Text.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
string newline = string.Empty;
gameListBox.Items.Clear();
ReadIntoArray();
string[][] games = new string[16][];
var index = BinSrchByName(nameTextBox.Text);
if (index != -1)
{
gameListBox.Items.Add(names[index] + " ==> $" + sales[index]);
}
else
{
MessageBox.Show("Data not found");
}

Please try the following (I wrote some comments to help you understand my method):
// Declare a list to hold the file lines
List<string> FileLines = new List<string>();
private void button_BrowseFile_Click(object sender, EventArgs e)
{
// Open a file dialog
using (OpenFileDialog openDialog = new OpenFileDialog())
{
// Set the file dialog to show only *.txt file or all files
openDialog.Filter = "Text files (*.txt)|*.txt|All Files (*.*)|*.*";
// Allow only single file selection
openDialog.Multiselect = false;
// Make sure the user didn't clicked the 'Cancel' button
if (openDialog.ShowDialog(this) == DialogResult.OK)
{
// Update the current file label with the filename only (not the full path)
label_CurrentFile.Text = $"Current file: {Path.GetFileName(openDialog.FileName)}";
// Add each line of the txt file into the list
foreach (string line in File.ReadAllLines(openDialog.FileName, Encoding.UTF8))
FileLines.Add(line);
}
}
}
private void button_DoSearch_Click(object sender, EventArgs e)
{
// Clear the list
list_SearchResults.Items.Clear();
// Count the number of line so you will be able to present it on the results list later on
int iLineNumber = 1;
// For each item in the 'FileLines' list
foreach (var item in FileLines)
{
// Check whether the current line contains the term the user typed in the searchbox
// I'm using 'ToLower()' to ignore case
if (item.ToLower().Contains(text_SearchTerm.Text.ToLower()))
{
// Create new ListViewItem to be added later on to the results list
// Add the first column the complete line that contains the term in the searchbox
ListViewItem lvi = new ListViewItem(item);
// Add the line number to the second column
lvi.SubItems.Add(iLineNumber.ToString());
// Add the ListviewItem to the results list
list_SearchResults.Items.Add(lvi);
}
// Increment the line number variable
iLineNumber++;
}
}
Screenshots:
Hope it helps!

This function receives the file path and the searched word and runs through the entire text file and returns the line where the requested word was found.
private string SearchText(string archivetxt, string word) {
StreamReader sr = new StreamReader(archivetxt);
while (!sr.EndOfStream) {
string s = sr.ReadLine();
if (s.IndexOf(word) > -1)
return s;
}
sr.Close();
return word + " not found";
}

Related

C# Forms read textBox1 all lines and delete given paths?

Good day!
I'm trying to create a C # Forms app where user chooses directories with FolderDialog and paths are saved in list.txt file after read by textBox1.
In list.txt user can add and delete path.
code snippet:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Lines = System.IO.File.ReadAllLines(fileName);
}
string fileName = Environment.CurrentDirectory + #"/etc/list.txt";
private void LoadTextboxes()
{
string[] loadedLines = System.IO.File.ReadAllLines(Environment.CurrentDirectory + #"/etc/list.txt");
int index = 0;
int n = int.Parse(loadedLines[index]);
string[] lines = new string[n];
Array.Copy(loadedLines, index + 1, lines, 0, n);
textBox1.Lines = lines;
}
private void DeleteFilesFromDirectory(string directoryPath)
{
DirectoryInfo d = new DirectoryInfo(directoryPath);
foreach (FileInfo fi in d.GetFiles())
{
fi.Delete();
}
foreach (DirectoryInfo di in d.GetDirectories())
{
DeleteFilesFromDirectory(di.FullName);
di.Delete();
}
}
private void button1_Del(object sender, EventArgs e)
{
DeleteFilesFromDirectory(textBox1.Text);
}
list.txt format:
C:/downloads
F:/doc/scan
D:/etc
t is important to delete only the sub folders and files but root folders must remain.
So far I have been done with my weak knowledge of c# and and now I'm stuck for a long time.
DeleteFilesFromDirectory only deletes the first line of textBox1.
How to make DeleteFilesFromDirectory read and delete all lines from textBox1?
Check this I tested it.
//put all paths in array reading line by line
string[] paths = System.IO.File.ReadAllLines(#"path-to\list.txt");
//get line by line paths
foreach (string path in paths)
{
if (Directory.Exists(path))
{
//deletes all files and parent
//recursive:true, deletes subfolders and files
Directory.Delete(path, true);
//create parent folder
Directory.CreateDirectory(path);
}
}//end outer for

Selenium find array contents on page

I'm using Visual Studio with Selenium to build an application that goes to a web page and finds if the contents of an array are on the page. I'm running into an issue with searching the page for the array contents.. Right now it finds nothing, so it clicks to go to the next page when it shouldn't.
The array comes from a CSV file I'm loading in and it needs to search the page for a match of any of the records from the CSV file and stops.
Here is what I have so far:
OpenFileDialog ofd = new OpenFileDialog();
private double timeOut;
private void bttnImportBrowse_Click(object sender, EventArgs e)
{
ofd.Filter = "CSV|*.csv";
var fileInputs = new List<string>();
if (ofd.ShowDialog() == DialogResult.OK)
{
String chosenFile = ofd.FileName;
String safeFileName = ofd.SafeFileName;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(chosenFile))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
fileInputs.Add(line);
//Console.Write(string.Join(" ", fileInputs));
var driver = new ChromeDriver(#"C:\Users\andre_000\Documents\Visual Studio 2015\Projects\MyProject\");
driver.Navigate().GoToUrl("MySite");
var WebDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((By.XPath("/html/body/a[2]"))));
while (1==1) {
try
{
var result = driver.FindElement(By.LinkText(fileInputs.ToString()));
break;
}
catch (NoSuchElementException n)
{
var nextBttn = driver.FindElementByXPath("/html/body/a[2]");
nextBttn.Click();
}
}
}
}
}
catch (Exception entry)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(entry.Message);
}
}
}
Sorry i would have left a comment but am not allowed to yet. Do you have the CSV file?
I believe you are trying to find the Link text incorrectly.
Currently calling ToString() on the list
var result = driver.FindElement(By.LinkText(fileInputs.ToString()));
should probably be
var result = driver.FindElement(By.LinkText(line));

Remove white space from a text file in Windows Forms Application

I have a file in the following text format:
sagchjvcsj kbschjsdchs sudbjsdbl avhsdvbas
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc kansjdnas ajksbdajsdk
with out of sequence white spaces between the words. I want to remove all the extra white spaces and leave only 1 white space between the words. My working is:
private void buttonBrowse_Click(object sender, EventArgs e)
{
openFileDialogImage.Filter = "Text files | .txt";
openFileDialogImage.Multiselect = false;
DialogResult result = openFileDialogImage.ShowDialog();
if (result == DialogResult.OK)
{
textBoxFileName.Text = openFileDialogImage.FileName;
}
}
private void buttonGo_Click(object sender, EventArgs e)
{
String path = openFileDialogImage.FileName;
using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open)))
{
string s = String.Empty;
while ((s = reader.ReadToEnd()) != null)
{
string[] parts = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
buttonBrowse is correctly displaying the file path in textBoxFileName but when I press the Go button (buttonGo), program is freezing with no output. Can someone please guide.
You're while loop never ends.
while ((s = reader.ReadToEnd()) != null)
That ReadToEnd returns a string every time it loops (when at the end it is an empty string - Not null.
If the current position is at the end of the stream, returns an empty
string
You need to either remove the while loop and just do:
s = reader.ReadToEnd()
or change null to string.Empty

Drag MP3's to ListView in C#

I am currently working on my own MP3 player and want to add drag & drop functionality to be able to drag & drop your music either a file at a time or a whole directory at a time. I have the View of my ListView set to details, and am using the following code:
void Playlist_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
void Playlist_DragDrop(object sender, DragEventArgs e)
{
Playlist.Items.Clear();
string[] songs = (string[])e.Data.GetData(DataFormats.FileDrop, false);
Parallel.ForEach(songs, s =>
{
if (File.Exists(s))
{
if (string.Compare(Path.GetExtension(s), ".mp3", true) == 0)
{
MessageBox.Show(s);
AddFileToListview(s);
}
}
else if (Directory.Exists(s))
{
DirectoryInfo di = new DirectoryInfo(s);
FileInfo[] files = di.GetFiles("*.mp3");
foreach (FileInfo file in files)
{
AddFileToListview(file.FullName);
MessageBox.Show(file.FullName);
}
}
});
}
private void AddFileToListview(string fullFilePath)
{
if (!File.Exists(fullFilePath))
return;
string song = Path.GetFileName(fullFilePath);
string directory = Path.GetDirectoryName(fullFilePath);
if (directory.EndsWith(Convert.ToString(Path.DirectorySeparatorChar)))
directory = directory.Substring(0, directory.Length - 1); //hack off the trailing \
ListViewItem itm = Playlist.Items.Add(song);
itm.SubItems.Add(directory); //second column = path
}
I have the MessageBox in there to make sure my code is being hit and tit always shows me the right data but nothing shows in the ListView. Any ideas what I'm doing wrong?
#ClearLogic: You were right I forgot to define columns in the ListView, thanks. Now I have another problem, I can drag multiple directories into the ListView with no problems, but when I try to add multiple single MP3's I get a cross-thread exception on the line
ListViewItem itm = Playlist.Items.Add(song);
Thanks to #ClearLogic for all their help in solving this issue, I thought I'd share my code in case someone else is having some issues as well.
private void Playlist_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void Playlist_DragDrop(object sender, DragEventArgs e)
{
//get the file names
string[] songs = (string[])e.Data.GetData(DataFormats.FileDrop, false);
//we're using a Parallel.ForEach loop because if a directory is selected it can contain n number of items, this is to help prevent a bottleneck.
Parallel.ForEach(songs, song =>
{
//make sure the file exists
if (File.Exists(song))
{
//if it's an mp3 file then call AddFileToListview
if (string.Compare(Path.GetExtension(song), ".mp3", true) == 0)
{
AddFileToListview(song);
}
}
//A HA! It's a directory not a single file
else if (Directory.Exists(song))
{
//get the directory information
DirectoryInfo di = new DirectoryInfo(song);
//get all the mp3 files (will add WMA in the future)
FileInfo[] files = di.GetFiles("*.mp3");
//here we use a parallel loop to loop through every mp3 in the
//directory provided
Parallel.ForEach(files, file =>
{
AddFileToListview(file.FullName);
});
}
});
}
private void AddFileToListview(string fullFilePath)
{
double nanoseconds;
string totalTime = string.Empty;
//First things first, does the file even exist, if not then exit
if (!File.Exists(fullFilePath))
return;
//get the song name
string song = Path.GetFileName(fullFilePath);
//get the directory
string directory = Path.GetDirectoryName(fullFilePath);
//hack off the trailing \
if (directory.EndsWith(Convert.ToString(Path.DirectorySeparatorChar)))
directory = directory.Substring(0, directory.Length - 1);
//now we use the WindowsAPICodePack.Shell to start calculating the songs time
ShellFile shell = ShellFile.FromFilePath(fullFilePath);
//get the length is nanoseconds
double.TryParse(shell.Properties.System.Media.Duration.Value.ToString(), out nanoseconds);
//first make sure we have a value greater than zero
if (nanoseconds > 0)
{
// double milliseconds = nanoseconds * 0.000001;
TimeSpan time = TimeSpan.FromSeconds(Utilities.ConvertToMilliseconds(nanoseconds) / 1000);
totalTime = time.ToString(#"m\:ss");
}
//build oour song data
ListViewItem item = new ListViewItem();
item.Text = song;
item.SubItems.Add(totalTime);
//now my first run at this gave me a cross-thread exception when trying to add multiple single mp3's
//but I could add all the whole directories I wanted, o that is why we are now using BeginINvoke to access the ListView
if (Playlist.InvokeRequired)
Playlist.BeginInvoke(new MethodInvoker(() => Playlist.Items.Add(item)));
else
Playlist.Items.Add(item);
}
This code uses the WindowsAPICodePack to calculate the time of each song.

C#. Using all files in a folder, and writing a different string in a specific line

I need your help.
The thing is that my code works, it reads all the files in a folder which are 96 text files and saves the path of each file.
I then take each file and change the line number 32 in the text file which is
"Treatment";"1"; nr = 1,2,3,4,5,...,96.
My program will takes this string and replaces it with a different one, I change the first file for example to "Treatment";"100"; then the last file should be "Treatment";"196";
So to solve this i change the whole line with a new one. But when i write the number to the string first file is right when i start from 1, but files 2-10 are. 12,23,34,45,56,67,78,89, then it starts 2,3,4,5,6,7 from the 11-th file.
Why is this? My code is below.
I tried saving the integer as a string because I though i was somehow accesing a ASCII table. But that works the same, so my code is below any ideas?
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
int start = 1;
string strengur = "\";";
string myString = start.ToString();
string[] filePaths = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
//foreach (var file in Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath))
for(int i = 0; i < 96 ; i++){
var lines = File.ReadAllLines(filePaths[i]);
lines[31] = "\"Treatment!!\";\"" +myString +strengur;
File.WriteAllLines(filePaths[i], lines);
start += 1;
myString = start.ToString();
}
}
}
Best Regards
Sæþór Ólafur Pétursson
Display all these files in windows explorer, sort by name, and then you will see why.
To solve it, you can set your start based on each file's line31's current number, and add by 100. E.g.:
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string strengur = "\";";
string[] filePaths = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach(var file in filePaths)
{
var lines = File.ReadAllLines(file);
int currentstart = int.Parse(lines[31].Split(';')[1].Trim('\"'));
lines[31] = "\"Treatment!!\";\"" + (currentstart+100).ToString() + strengur;
File.WriteAllLines(file, lines);
}
}
}
Edit based on your comment:
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
int start = 100; //set this to your user's input
string strengur = "\";";
string[] filePaths = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach(var file in filePaths)
{
var lines = File.ReadAllLines(file);
int currentstart = int.Parse(lines[31].Split(';')[1].Trim('\"'));
lines[31] = "\"Treatment!!\";\"" + (currentstart+start-1).ToString() + strengur;
File.WriteAllLines(file, lines);
}
}
}

Categories

Resources