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));
Related
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";
}
I have the following code to get Text file as input from the user.I would like to change the code to read the input text file and store each line in array.I am using c# console application.
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Filter = "CBL files (*.CBL)|*.cbl";
if (op.ShowDialog() == DialogResult.OK)
{
textBox1.Text = op.FileName;
string path = op.FileName;
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.AppendLine(sr.ReadToEnd());
}
richTextBox1.Text = sb.ToString();
}
}
}
Please help as I am new to coding.
To answer your specific question, you can do the following:
string[] lines = sb.ToString().Split(Environment.NewLine.ToCharArray());
However, this is a lot of overkill for what it is you are actually trying to do. There is a prebuilt method for reading a file into a string array:
string[] lines = File.ReadAllLines(op.FileName);
My issue is that I keep seeing a recurring theme with trying to allow my Notepad clone to save a file. Whenever I try to save a file, regardless of the location on the hard disk, the UnauthorizedAccess Exception continues to be thrown. Below is my sample code for what I've done, and I have tried researching this since last night to no avail. Any help would be greatly appreciated.
//located at base class level
private const string fileFilter = "Text Files|*.txt|All Files|*.*";
private string currentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private void MenuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "*.txt";
sfd.Filter = fileFilter;
sfd.AddExtension = true;
sfd.InitialDirectory = currentPath;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
sfd.ShowDialog();
try
{
System.IO.File.WriteAllText(currentPath,TxtBox.Text,Encoding.UTF8);
}
catch (ArgumentException)
{
// Do nothing
}
catch(UnauthorizedAccessException)
{
MessageBox.Show("Access Denied");
}
}
Change the following lines.
...
if (sfd.ShowDialog() != true)
return;
try
{
using (var stream = sfd.OpenFile())
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(TxtBox.Text);
}
}
...
I hope it helps you.
You need to get the correct path context and file object from the dialog box once the user has hit 'ok'. Namely verify the user actually hit ok and then use the OpenFile property to see what their file selection is:
if (sfd.ShowDialog.HasValue && sfd.ShowDialog)
{
if (sfd.OpenFile() != null)
{
// convert your text to byte and .write()
sfd.OpenFile.Close();
}
}
I've searched multiple solutions and coudnt find the one specificly adressing my issue:
What i want to accomplish is to save a state of checkbox to specific line of file.
I have used identical code for saving patch of file from openFileDialog.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var lines = File.ReadAllLines("patcher.conf");
lines[0] = openFileDialog1.FileName;
File.WriteAllLines("patcher.conf", lines);
}
code above saves file patch in 1st (0 indexed) line of text file, and it works!
But for some reason when i try to do exacly the same thing in :
private void checkexe_CheckedChanged(object sender, EventArgs e)
{
string line;
System.IO.StreamReader file =
new System.IO.StreamReader("patcher.conf");
while ((line = file.ReadLine()) != null)
{
var lines = File.ReadAllLines("patcher.conf");
lines[1] = checkexe.Checked.ToString();
File.WriteAllLines("patcher.conf", lines);
}
file.Close();
}
and save information about state of checkbox in 2nd (1 indexed line of file) the error says :
process cannot access the file because it is being used by another process.
What i do wrong?
Your method for writing the file is flawed. You are opening the file and reading all lines, but for every line, you are then reading all lines again and saving the file in the same loop. This would be the cause of your process cannot access the file because it is being used by another process error.
private void checkexe_CheckedChanged(object sender, EventArgs e)
{
string line;
System.IO.StreamReader file = new System.IO.StreamReader("patcher.conf");
while ((line = file.ReadLine()) != null)
{
var lines = File.ReadAllLines("patcher.conf");
lines[1] = checkexe.Checked.ToString();
File.WriteAllLines("patcher.conf", lines);
}
file.Close();
}
Instead, try below: (untested, but should get you in the right direction)
private void checkexe_CheckedChanged(object sender, EventArgs e)
{
var lines = File.ReadAllLines("patcher.conf");
for(var i = 0; i < lines.Length; i++)
{
if (i == 1)
lines[i] = checkexe.Checked.ToString();
}
File.WriteAllLines("patcher.conf", lines);
}
On the file stream, you have use readwrite
System.IO.FileStream fs = new System.IO.FileStream(txtFilePath.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.FileShare.ReadWrite);
System.IO.StreamReader sr = new System.IO.StreamReader(fs);
The following are my codes but it cant handle more than 500 lines at one time.
It needs to add a , to the end of the line and at the same time detect. What i'm currently doing is separating them into 2 different textbox then save the one which i need by copy pasting but the app seems to hang if the file is too big.
Can someone help me with making it more efficient. Would really appreciate it.
private void button1_Click_1(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
return;
System.IO.StreamReader Reader = new System.IO.StreamReader(openFileDialog1.FileName);
//Create a filestream
FileStream fStr;
try
{
//Set filestream to the result of the pick of the user
fStr = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
//Create a streamreader, sr, to read the file
StreamReader sr = new StreamReader(fStr);
//While the end of the file has not been reached...
while (sr.Peek() >= 0)
{
//Create a 'line' that contains the current line of the textfile
string line = sr.ReadLine().ToLower();
if (line.Contains("staff"))
{
line += ","; //Add a , to the end of the line**Important**
textBox1.Text += line + Environment.NewLine;
releventcount += 1;
}
else
{
line += ","; //Add a , to the end of the line**Important**
textBox2.Text += line + Environment.NewLine;
irreleventcount += 1;
}
label1.Text = "Relevent: ";
label2.Text = "Irrelevant: ";
}
//Close the file so other modules can access it
sr.Close();
//If something goes wrong, tell the user
}
catch (Exception)
{
MessageBox.Show("Error opening file", "Check the CODE ! ~.~");
}
}
I'm not sure what it is you're eventually trying to accomplish here. There are several more succinct ways to do what your current code is doing, but they won't significantly improve the speed of reading.
The bottleneck in your code is that you're appending strings. Using a StringBuilder is good advice, but you can do better than that by creating a List<string> and then calling string.Join at the end. For example:
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
return;
List<string> staff = new List<string>();
List<string> other = new List<string>();
foreach (var line in File.ReadLines(openFileDialog1.FileName))
{
line = line.ToLower();
if (line.Contains("staff"))
{
staff.Add(line);
}
else
{
other.Add(line);
}
}
relevantcount = staff.Count;
irrelevantCount = other.Count;
textBox1.Text = string.Join(","+Environment.NewLine, staff);
textBox2.Text = string.Join("."+Environment.NewLine, other);
Also, you say that your code can only handle 500 lines at a time. Is there something in your user interface that prevents it from handling more? Certainly, there's nothing in the code you showed that has such a low limit.
500 lines is nothing.
Try File.ReadAllLines and File.WriteAllLines.
Then you can do your work on an array of strings in memory and avoid the iterative IO.
Reading files line by line is very slow. You can make this code much faster by reading a large block of data (or even the entire file if it's not too enormous). For example, use a File.ReadAllLines to read the entire file as separate lines, or use a FileStream and Read() into a buffer, and find the individual lines for yourself by looking for newline (\n, \r) characters.
To export the data, don't copy and paste it fom a text box - Write the results to one or two new files, and then just open them.
It is much, much more efficient to use StringBuilders to gather the text for the textboxes than to continuously append text.
Also, you should wrap your various streams in using blocks.
Here is a rewrite that should be much more efficient:
private void button1_Click_1(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
return;
try
{
//Set filestream to the result of the pick of the user
using (var fStr = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read))
{
//Create a streamreader, sr, to read the file
using (var sr = new StreamReader(fStr))
{
var sbTextBox1 = new System.Text.StringBuilder(10000);
var sbTextBox2 = new System.Text.StringBuilder(10000);
//While the end of the file has not been reached...
while (sr.Peek() >= 0)
{
//Create a 'line' that contains the current line of the textfile
string line = sr.ReadLine().ToLower();
if (line.Contains("staff"))
{
//Add a , to the end of the line**Important**
sbTextBox1.Append(line).Append(",").AppendLine();
releventcount += 1;
}
else
{
//Add a , to the end of the line**Important**
sbTextBox2.Append(line).Append(",").AppendLine();
irreleventcount += 1;
}
}
textBox1.Text = sbTextBox1.ToString();
textBox2.Text = sbTextBox2.ToString();
label1.Text = "Relevent: ";
label2.Text = "Irrelevant: ";
//Close the file so other modules can access it
sr.Close();
}
}
}
catch (Exception)
{
MessageBox.Show("Error opening file", "Check the CODE ! ~.~");
}
}