c# writing text to different selected listboxes and refresh - c#

I am pretty new to c# and have small task to do. At the moment I have code which reads directories and add.ini files to different listboxes depending on statement in it (this part seems to work perfectly for me). Now then I select item in my listbox2 and press button it write specific word in my selected .ini file. (this part seems to work as well), but here comes my problem... I want to write other word to .ini file with same button from listbox1. I cant wrap my head around how to make it with same button. I figure my problem is somewhere here. Also maybe you know how to update my listboxes after I change statement in .ini files? Thanks
private void button1_Click(object sender, EventArgs e)
{
var items = listBox2.SelectedItems;
//var items1 = listBox1.SelectedItems;
foreach (var item in items)
{
string fileName = listBox2.GetItemText(item);
string text = File.ReadAllText(fileName);
My entire code
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string rootdir = #"C:\Users\isaced1\Desktop\test";
string[] files = Directory.GetFiles(rootdir, "*.ini", SearchOption.AllDirectories);
foreach (string item in files)
{
string fileContents = File.ReadAllText(item);
const string PATTERN = #"OTPM = true";
Match match = Regex.Match(fileContents, PATTERN, RegexOptions.IgnoreCase);
if (match.Success)
{
listBox1.Items.Add(item);
listBox1.ForeColor = Color.Green;
}
else
{
listBox2.Items.Add(item);
listBox2.ForeColor = Color.Red;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
//listBox2.SelectedItem = listBox1.SelectedItem;
var items = listBox2.SelectedItems;
//var items1 = listBox1.SelectedItems;
foreach (var item in items)
{
string fileName = listBox2.GetItemText(item);
string text = File.ReadAllText(fileName);
const string PATTERN = #"OTPM = (?<Number>[false]+)";
Match match = Regex.Match(text, PATTERN, RegexOptions.IgnoreCase);
string otpmT = "true";
string otpmF = "false";
if (match.Success)
{
int index = match.Groups["Number"].Index;
int length = match.Groups["Number"].Length;
text = text.Remove(index, length);
text = text.Insert(index, otpmT.ToString());
File.WriteAllText(fileName, text);
Process.Start(fileName);
}
else
{
int index = match.Groups["Number"].Index;
int length = match.Groups["Number"].Length;
text = text.Remove(index, length);
text = text.Insert(index, otpmF.ToString());
File.WriteAllText(fileName, text);
Process.Start(fileName);
}
}
}
}

If i understand correctly, you just have to do the same thing again but for your other listbox :
private void button1_Click(object sender, EventArgs e)
{
// ------------------------------ Listbox2
var items = listBox2.SelectedItems;
foreach (var item in items)
{
string fileName = listBox2.GetItemText(item);
string text = File.ReadAllText(fileName);
const string PATTERN = #"OTPM = (?<Number>[false]+)";
Match match = Regex.Match(text, PATTERN, RegexOptions.IgnoreCase);
string otpmT = "true";
string otpmF = "false";
if (match.Success)
{
int index = match.Groups["Number"].Index;
int length = match.Groups["Number"].Length;
text = text.Remove(index, length);
text = text.Insert(index, otpmT.ToString());
File.WriteAllText(fileName, text);
Process.Start(fileName);
}
else
{
int index = match.Groups["Number"].Index;
int length = match.Groups["Number"].Length;
text = text.Remove(index, length);
text = text.Insert(index, otpmF.ToString());
File.WriteAllText(fileName, text);
Process.Start(fileName);
}
}
// ------------------------------ Listbox1
var items1 = listBox1.SelectedItems;
foreach (var item in items1)
{
string fileName = listBox1.GetItemText(item);
string text = File.ReadAllText(fileName);
const string PATTERN = #"OTPM = (?<Number>[false]+)";
Match match = Regex.Match(text, PATTERN, RegexOptions.IgnoreCase);
string otpmT = "true";
string otpmF = "false";
if (match.Success)
{
int index = match.Groups["Number"].Index;
int length = match.Groups["Number"].Length;
text = text.Remove(index, length);
text = text.Insert(index, otpmT.ToString());
File.WriteAllText(fileName, text);
Process.Start(fileName);
}
else
{
int index = match.Groups["Number"].Index;
int length = match.Groups["Number"].Length;
text = text.Remove(index, length);
text = text.Insert(index, otpmF.ToString());
File.WriteAllText(fileName, text);
Process.Start(fileName);
}
}
}
In this code I duplicate the code for listbox2, you just have to change what to check / what to write.
When the button is clicked both listboxes are proceed.

Related

Remove accents from a text file

I have issues with removing accents from a text file program replaces characters with diacritics to ? Here is my code:
private void button3_Click(object sender, EventArgs e)
{
if (radioButton3.Checked)
{
byte[] tmp;
tmp = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(richTextBox1.Text);
richTextBox2.Text = System.Text.Encoding.UTF8.GetString(tmp);
}
}
Taken from here: https://stackoverflow.com/a/249126/3047078
static string RemoveDiacritics(string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
usage:
string result = RemoveDiacritics("včľťšľžšžščýščýťčáčáčťáčáťýčťž");
results in vcltslzszscyscytcacactacatyctz
richTextBox1.Text = "včľťšľžšžščýščýťčáčáčťáčáťýčťž";
string text1 = richTextBox1.Text.Normalize(NormalizationForm.FormD);
string pattern = #"\p{M}";
string text2 = Regex.Replace(text1, pattern, "�");
richTextBox2.Text = text2;
First normalize the string.
Then with a regular expression replace all diacritics. Pattern \p{M} is Unicode Category - All diacritic marks.

How to implement if before while

My code goes like this:
public void button1_Click(object sender, EventArgs e)
{
StreamReader tx = null;
if (textBox1.Text != "")
{
tx = new StreamReader(textBox1.Text);
}
else
{
tx = new StreamReader("new.txt");
}
string line;
while ((line = tx.ReadLine()) != null)
{
string url = (line);
string sourceCode = Worker.getSourceCode(url);
MatchCollection m1 = Regex.Matches(sourceCode, #"title may-blank "" href=""(.+?)""", RegexOptions.Singleline);
MatchCollection m2 = Regex.Matches(sourceCode, #"(?<=tabindex=\""1\"" \>| tabindex=\""1\"" rel=""nofollow"" \>)(.+?) (?=<\/a>)", RegexOptions.Singleline);
List<string> adresy = new List<string>();
List<string> nazwy = new List<string>();
int counter = 0;
foreach (Match m in m1)
{
string adres = m.Groups[1].Value;
adresy.Add(adres);
counter++;
label1.Text = counter.ToString();
}
int counter2 = 0;
foreach (Match m in m2)
{
string nazwa = m.Groups[1].Value;
nazwy.Add(nazwa);
counter2++;
label2.Text = counter2.ToString();
}
listBox1.DataSource = adresy;
listBox2.DataSource = nazwy;
}
}
I am using RegEx to scrape text from web pages. And the thing is, that I want to scrape single URL if that URL is in textBox1. But if textbox1 is empty, I want to scrape all the URL's from new.txt file.
So... I have to implement "if" but I don't really know how to. I mean, it should go like this:
if textbox1 is empty
then read from single line
if not, then read from new.txt
do stuff like scraping..
But as you can see in my code which is upper, it doesn't work properly. I mean it works, but only if I read from new.txt. When I add some text to textbox1.Text and try to scrape URL, my app is crashing. I assume that it crashes, because I shouldn't have used streamreader to read from textbox. I don't know. Do you have any ideas?
If you want to write your code like this, then you can use a StringReader:
TextReader tx = null;
if (textBox1.Text != "")
{
tx = new StringReader(textBox1.Text);
}
else
{
tx = new StreamReader("new.txt");
}
Make sure to wrap your code in a try/finally block and call tx.Dispose() in the finally.

Reading txt file line by line than than write all lines to the RichTextBox

when i click to button it'll take these links from c:\text.txt file and it will write into my richtextbox
in my text.txt:
en.wikipedia.org/wiki/Extreme_programming
en.wikipedia.org/wiki/Boolean_algebra
en.wikipedia.org/wiki/Microsoft_Visual_Studio
en.wikipedia.org/wiki/Web_crawler
(there is no empty rows between links)
after that i want to call that links line by line into my other button to parse its html codes and write to other richtextbox
here is my parse button code:
private void button2_Click(object sender, EventArgs e)
{
string s = KaynakKodunuCek("http://tr.wikipedia.org/wiki/Lale");
// <p ... > </p> tagları arasını alıyor.(taglar dahil)
Regex regex = new Regex("<p[^>]*>.*?</p>");
string gelen = s;
string inside = null;
Match match = regex.Match(gelen);
if (match.Success)
{
inside = match.Value;
richTextBox3.Text = inside;
}
string outputStr = "";
foreach (Match ItemMatch in regex.Matches(gelen))
{
Console.WriteLine(ItemMatch);
inside = ItemMatch.Value;
//boşluk bırakıp alt satıra yazıyor
outputStr += inside + "\r\n";
}
richTextBox3.Text = outputStr;
}
here i want to call links string s = KaynakKodunuCek("here");
Or should i use listbox instead of richtextbox
Yes, listBox would be better.But if you want to do it with richTexBox you can use this:
string[] links = richTextBox2.Text.Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
for(int i=0;i<links.Length;i++)
{
string s = KaynakKodunuCek(links[i]);
...
}

c# read value from file and ignore everything except for value

I have a program that I need to have a config file with value to be
displayed in my program. Inside my text file I have Wireless = 1
& Cradle = 2.
In my program I will have a label populate the release number only and not the other
characters.
private string searchFile(String path, String searchText)
{
string regex=#"(?i)(?<="+searchText+#"\s*=\s*)\d+";
return Regex.Match(File.ReadAllText(path),regex).Value;//version number
}
This is what I tried and it gives the correct output
string s="Wireless = 1 Cradle = 2";
Regex.Match(s,#"(?i)(?<=Wireless\s*=\s*)\d+").Value;//1
public static string match;
public static string ReadAllText(string path)
{
using (var r = new System.IO.StreamReader(path))
{
return r.ReadToEnd();
}
}
private string Wireless(String path, String searchText)
{
string regex = #"(?i)(?<=" + searchText + #"\s*=\s*)\d+";
match = Regex.Match(ReadAllText(path), regex).Value;
label1.Text = match;
return match;
}
private string Cradle(String path, String searchText)
{
string regex = #"(?i)(?<=" + searchText + #"\s*=\s*)\d+";
match = Regex.Match(ReadAllText(path), regex).Value;
label2.Text = match;
return match;
}
private void button1_Click(object sender, EventArgs e)
{
Wireless(#"\Storage Card\changelog.txt","Wireless");
Cradle(#"\Storage Card\changelog.txt", "Cradle");
}

Remove words from string c#

I am working on a ASP.NET 4.0 web application, the main goal for it to do is go to the URL in the MyURL variable then read it from top to bottom, search for all lines that start with "description" and only keep those while removing all HTML tags. What I want to do next is remove the "description" text from the results afterwords so I have just my device names left. How would I do this?
protected void parseButton_Click(object sender, EventArgs e)
{
MyURL = deviceCombo.Text;
WebRequest objRequest = HttpWebRequest.Create(MyURL);
objRequest.Credentials = CredentialCache.DefaultCredentials;
using (StreamReader objReader = new StreamReader(objRequest.GetResponse().GetResponseStream()))
{
originalText.Text = objReader.ReadToEnd();
}
//Read all lines of file
String[] crString = { "<BR> " };
String[] aLines = originalText.Text.Split(crString, StringSplitOptions.RemoveEmptyEntries);
String noHtml = String.Empty;
for (int x = 0; x < aLines.Length; x++)
{
if (aLines[x].Contains(filterCombo.SelectedValue))
{
noHtml += (RemoveHTML(aLines[x]) + "\r\n");
}
}
//Print results to textbox
resultsBox.Text = String.Join(Environment.NewLine, noHtml);
}
public static string RemoveHTML(string text)
{
text = text.Replace(" ", " ").Replace("<br>", "\n");
var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
return oRegEx.Replace(text, string.Empty);
}
Ok so I figured out how to remove the words through one of my existing functions:
public static string RemoveHTML(string text)
{
text = text.Replace(" ", " ").Replace("<br>", "\n").Replace("description", "").Replace("INFRA:CORE:", "")
.Replace("RESERVED", "")
.Replace(":", "")
.Replace(";", "")
.Replace("-0/3/0", "");
var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
return oRegEx.Replace(text, string.Empty);
}
public static void Main(String[] args)
{
string str = "He is driving a red car.";
Console.WriteLine(str.Replace("red", "").Replace(" ", " "));
}
Output:
He is driving a car.
Note: In the second Replace its a double space.
Link : https://i.stack.imgur.com/rbluf.png
Try this.It will remove all occurrence of the word which you want to remove.
Try something like this, using LINQ:
List<string> lines = new List<string>{
"Hello world",
"Description: foo",
"Garbage:baz",
"description purple"};
//now add all your lines from your html doc.
if (aLines[x].Contains(filterCombo.SelectedValue))
{
lines.Add(RemoveHTML(aLines[x]) + "\r\n");
}
var myDescriptions = lines.Where(x=>x.ToLower().BeginsWith("description"))
.Select(x=> x.ToLower().Replace("description",string.Empty)
.Trim());
// you now have "foo" and "purple", and anything else.
You may have to adjust for colons, etc.
void Main()
{
string test = "<html>wowzers description: none <div>description:a1fj391</div></html>";
IEnumerable<string> results = getDescriptions(test);
foreach (string result in results)
{
Console.WriteLine(result);
}
//result: none
// a1fj391
}
static Regex MyRegex = new Regex(
"description:\\s*(?<value>[\\d\\w]+)",
RegexOptions.Compiled);
IEnumerable<string> getDescriptions(string html)
{
foreach(Match match in MyRegex.Matches(html))
{
yield return match.Groups["value"].Value;
}
}
Adapted From Code Project
string value = "ABC - UPDATED";
int index = value.IndexOf(" - UPDATED");
if (index != -1)
{
value = value.Remove(index);
}
It will print ABC without - UPDATED

Categories