Save a state of checkbox to specific line of file C # - c#

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

Related

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

How do i change the stringbuilder to array in c#

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

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

How to copy contents of one text file to another with reduced length?

I have a text file with about 5,000 lines and I want to copy its contents to another file, but only the first 38 characters of each line.
I currently have this code:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
using (System.IO.StreamWriter files = new System.IO.StreamWriter(#"C:\test2.txt"))
{
files.WriteLine(line2);
}
}
file.Close();
}
It only copies the last line. :(
because you rewrite your new file in your loop. You should create your new string in the loop (use a stringBuilder for this will be more efficient), but write the new file out of the loop :
string line;
var sb = new StringBuilder();
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while ((line = file.ReadLine()) != null)
sb.AppendLine(line.Substring(0, Math.Min(38, line.Length)));
file.Close();
using (System.IO.StreamWriter files = new System.IO.StreamWriter(#"C:\test2.txt"))
{
files.WriteLine(sb.ToString());
}
or to do it shorter
var result = File.ReadAllLines(#"c:\test.txt")
.Select(m => m.Substring(0, Math.Min(38, m.Length)));
File.WriteAllLines(#"C:\test2.txt", result);
You need to move the creation of 'file2' before the while loop.
You should also create 'file' in a using:. You won't need to call close for either one then.
private void button1_Click(object sender, EventArgs e)
{
string line;
using (System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt"))
using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(#"C:\test2.txt"))
while ((line = file.ReadLine()) != null)
{
string line2 = line.Substring(0, 38);
file2.WriteLine(line2);
}
}
Your file's .WriteLine overwrites the entire file every time you call it. Therefore, put the entire code in your using block, or add true to the StreamWriter's arguments to tell it to append to the file instead of overwriting.
Option 1:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
using (System.IO.StreamWriter files = new System.IO.StreamWriter(#"C:\test2.txt"))
{
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
files.WriteLine(line2);
}
file.Close();
}
}
Option 2:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
using (System.IO.StreamWriter files = new System.IO.StreamWriter(#"C:\test2.txt",true))
{
files.WriteLine(line2);
}
}
file.Close();
}
And finally, if you choose to use a StringBuilder, you can use System.IO.File.WriteAllText(#"C:\test2.txt", stringHere); instead of the entire using and StreamWriter block

Making Reading of TextFile More efficient (Larger File Type)

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 ! ~.~");
}
}

Categories

Resources