When I open a file (I made myself) I need to use somethings out of the string of text that comes trough. I want to use some parts of the text as coordinates to draw a graph with.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
char XgetalEen;
char XgetalTwee;
char YgetalEen;
char Ygetaltwee;
string XgetalSamen = "";
string YgetalSamen = "";
int coordinaatX;
int coordinaatY;
DialogResult lel = MessageBox.Show("Do you want to close this file?", "OPEN", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (lel == DialogResult.Yes)
{
Open();
foreach(string s in Gcowde)
{
XgetalEen = s[5];
XgetalTwee = s[6];
YgetalEen = s[8];
Ygetaltwee = s[9];
XgetalSamen += XgetalEen + XgetalTwee;
YgetalSamen += YgetalEen + Ygetaltwee;
if(XgetalTwee==' ')
{
XgetalSamen = "";
XgetalTwee = '0';
XgetalSamen += XgetalTwee + XgetalEen;
YgetalEen = s[7];
Ygetaltwee = s[8];
YgetalSamen = "";
YgetalSamen += YgetalEen + Ygetaltwee;
}
if(Ygetaltwee==' ')
{
Ygetaltwee = '0';
YgetalSamen = "";
YgetalSamen += Ygetaltwee + YgetalEen;
}
MessageBox.Show(XgetalSamen + " " + YgetalSamen);
Int32.TryParse(XgetalSamen, out coordinaatX);
Int32.TryParse(YgetalSamen, out coordinaatY);
currentLocation.X += coordinaatX;
currentLocation.Y += coordinaatY;
Coord.Add(new Point(currentLocation.X, currentLocation.Y));
}
drawerryting();
}
}
public void Open()
{
Gcowde.Clear();
listBox1.Items.Clear();
Coord.Clear();
werkVlak.Clear(Color.Black);
Coord.Add(new Point(pictureBox1.Width / 2, pictureBox1.Height / 2));
drawerryting();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
string errything = sr.ReadToEnd();
string charAdded = "";
foreach (char s in errything)
{
if (s == '\n')
{
Gcowde.Add(charAdded);
charAdded = "";
}
else
{
charAdded += s;
}
}
foreach (string s in Gcowde)
{
listBox1.Items.Add(s);
}
sr.Close();
}
This is the code how I open the file and get the coordinates out of the string. The string is of this kind L1 G2 X50 Y50. i need to get the 2 50s out of the string.
ps.: the variables are in dutch.
XgetalEen = XnumberOne, XgetalTwee=XnumberTwo,
same goes for Y.
XgetalSamen=XnumberTogether, YgetalSamen=YnumberTogether.
This is a simple example how you could parse the file:
// Read your file using File.ReadAllLines
String[] lines = new[] { "L1 G2 X50 Y50", "L1 G2 X50 Y50" };
foreach (var line in lines)
{
String[] values = line.Split(' ');
string x = values.Where(s => s.StartsWith("X")).First().Replace("X", String.Empty);
int xCoordinate = Convert.ToInt32(x);
}
Don't forget to add all necessary checks and reading of other variables.
Related
I am trying to create a program that will replace a string inside .txt file.
heres the trick. I am replacing the string in the file if they are checked,
but when I do an alternate check its still replacing the other.
private void BatchReplace()
{
string sourceFolder = FilePath.Text;
string searchWord = Searchbar.Text;
DateTime now = DateTime.Now;
List<string> allFiles = new List<string>();
AddFileNamesToList(sourceFolder, allFiles);
if (listView1.CheckedItems.Count != 0)
{
foreach (String file in allFiles)
{
for (int x = 0; x <= listView1.CheckedItems.Count - 1; x++)
{
if (file.Contains(listView1.CheckedItems[x].Text))
{
MessageBox.Show("File contains: " + listView1.CheckedItems[x].Text);
try
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to replace \"" + Searchbar.Text + "\" with \"" + Replacebar.Text + "\"?", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
StreamReader reader = new StreamReader(file);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, Searchbar.Text, Replacebar.Text);
StreamWriter writer = new StreamWriter(file);
writer.Write(content); writer.Close();
}
else
{
}
}
catch
{
}
}
}
}
}
}
else
{
MessageBox.Show("Please Check the files you want to rename");
}
}
public static void AddFileNamesToList(string sourceDir, List<string> allFiles)
{
string[] fileEntries = Directory.GetFiles(sourceDir);
try
{
foreach (string fileName in fileEntries)
{
allFiles.Add(fileName);
}
//Recursion
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir);
foreach (string item in subdirectoryEntries)
{
// Avoid "reparse points"
if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
AddFileNamesToList(item, allFiles);
}
}
}
I am still confused about what you are trying to do, but to simplify things, why don't you, when you populate the ListView with the files in the directory, add the file path (or a file object) to the tag property of the ListViewitem?
That way, when you loop through the checked items, you can just retrieve the file directly instead of having to loop through two Lists at once.
Something like:
private void BatchReplace()
{
string sourceFolder = FilePath.Text;
string searchWord = Searchbar.Text;
AddFileNamesToList(sourceFolder);
if (listView1.CheckedItems.Count == 0)
{
MessageBox.Show("Please Check the files you want to rename");
return;
}
for (int x = 0; x < listView1.CheckedItems.Count; x++)
{
var file = listView1.CheckedItems[x].Tag.ToString()
try
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to replace \"" + Searchbar.Text + "\" with \"" + Replacebar.Text + "\"?", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
StreamReader reader = new StreamReader(file);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, SearchWord, Replacebar.Text);
StreamWriter writer = new StreamWriter(file);
writer.Write(content);
writer.Close();
}
}
catch
{
}
}
}
}
Sorry for the indenting and also if this doesn't work straight as is, I haven't tested this.
I want to extract text from web page at a run time then, use alchemy api in asp.net with c# but I don't know how to use this api in c#. I am trying to find out what the parameter of text extractor is. If needed I can also try to regular expression for extracting the web page but this was not clean html tags.
private void Form3_Load(object sender, EventArgs e)
{
}
void GetPosition(Uri url, string searchTerm)
{
string raw = "http://www.google.co.in/search?num=39&q={0}&btnG=Search"; string search = string.Format(raw,
HttpUtility.UrlEncode(searchTerm)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search); using (HttpWebResponse
response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader
reader = new StreamReader(response.GetResponseStream(),
Encoding.ASCII))
{
string html = reader.ReadToEnd();
//return FindPosition(html, url);
fillgoogle(html);
}
}
}
//New Fill Google
void fillgoogle(string html)
{
listBox1.Items.Clear();
// string pattern = #"h3 class=";
string pattern = "<h3 class=\"r\"><a href=";
/*for (int i = 0; i < 10; i++)
{
int start;
int end;
int pos;
pos = html.IndexOf(pattern);
start = html.IndexOf("href=", pos);
end = html.IndexOf("/", start + 15);
ListBox1.Items.Add(prepare(html.Substring(start + 6, end - start)));
html = html.Substring(end);
}*/
// int start;
int end;
int pos;
// string[] strUrl;
pos = html.IndexOf(pattern);
string[] Arr = Regex.Split(html, pattern);
for (int x = 1; x <= Arr.Length - 1; x++)
{
//string find = Arr[x].ToString();
//string RealData=find.Substring
// listBox1.Items.Add(Arr[x].ToString());
end = Arr[x].IndexOf("/", 38);
str1 = Arr[x].Substring(0, end);
// strUrl = Regex.Split(Arr[1], "&");
//string n = string.Join("/url?q=", Arr);
str1 = str1.Replace('"', ' ');
str1 = str1.Trim();
str1 = str1.Remove(0, 7).ToString();
listBox1.Items.Add(str1);
// ListBox1.Items.Add(Arr[x].Substring(0, end));
if (x == 10)
{
break;
}
}
}
void finalList()
{
listBox2.Items.Clear();
for (int i = 0; i < listBox1.Items.Count; i++)
{
string Link = listBox1.Items[i].ToString();
if (Link.IndexOf("&") != -1)
{
int end = Link.IndexOf("&");
string real = Link.Substring(0, end);
listBox2.Items.Add(real);
//MessageBox.Show(real);
}
}
}
string prepare(string url)
{
string temp;
int i;
i = url.IndexOf("//");
int j;
j = url.IndexOf("/", i + 3);
temp = url.Substring(0, j);
return (temp);
}
private static int FindPosition(
string html, Uri url)
{// h3 class=\"r\"><a href=\"http://www.godaddy.com/\
string lookup = "(<h3 class=r><a href=\")(\\*)";
MatchCollection matches = Regex.Matches(html, lookup);
for (int i = 0; i < matches.Count; i++)
{
string match = matches[i].Groups[2].Value;
if (match.Contains(url.Host))
return i + 1;
} return 0;
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
Uri url = new Uri("http://www.godaddy.com");
GetPosition(url, textBox1.Text);
finalList();
webPage page = new webPage();
page.URL = listBox2.Items[0].ToString();
page.Load(); //Load the text from the specified URL
label3.Visible = true;
linkLabel1.Visible = true;
label3.Text = listBox2.Items[0].ToString();
//Display the page TITLE on the screen
//richTextBox1.Text = "Title: " + page.Title + Environment.NewLine + Environment.NewLine;
//Display a list of INTERNAL links on the screen (to include external links, see below)
//richTextBox1.Text += "LINKS" + Environment.NewLine + "=====" + Environment.NewLine;
//foreach (String link in page.LinksArray)
//{
// richTextBox1.Text += link + Environment.NewLine;
//}
//Display the BODY TEXT on the screen
richTextBox1.Text += Environment.NewLine + page.Body;
//richTextBox1.Text += Environment.NewLine + page.Paragraph;
}
public class webPage
{
public String URL;
private String sTitle;
private String sBody;
private String sParagraph;
private ArrayList aList;
public String Title
{
get
{
return sTitle;
}
}
public ArrayList LinksArray
{
get
{
return aList;
}
}
public String Body
{
get
{
return sBody;
}
}
public String Paragraph
{
get
{
return sParagraph;
}
}
public void Load()
{
try
{
WebRequest objRequest = WebRequest.Create(this.URL);
WebResponse objResponse = objRequest.GetResponse();
StreamReader oSR = new StreamReader(objResponse.GetResponseStream());
string strContent = oSR.ReadToEnd();
this.sTitle = getTitle(strContent);
this.aList = fetchLinks(strContent, URL);
this.sBody = fetchText(strContent);
this.sParagraph = GetFirstParagraph(strContent);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private String getTitle(String sHTMLContent)
{
//Retrieve the title from the HTML code
return Regex.Match(sHTMLContent, "<title>(?<title>[^<]+)</title>", RegexOptions.IgnoreCase).Groups["title"].ToString();
}
private ArrayList fetchLinks(String sHTMLContent, String sURL)
{
//Find all the links in the HTML code and put them
//into an array
Match mMatch;
ArrayList aMatch = new ArrayList();
mMatch = Regex.Match(sHTMLContent, "href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))", RegexOptions.IgnoreCase);
while (mMatch.Success)
{
String sMatch = processURL(mMatch.Groups[1].ToString(), sURL);
//Currently, this code only lists INTERNAL URLs. If you would
//like to include EXTERNAL URLs as well, comment out the fol-
//lowing IF statement EXCEPT the "aMatch.Add(sMatch);" line
if (sMatch.IndexOf(sURL) >= 0 && checkFormat(sMatch))
{
aMatch.Add(sMatch);
}
mMatch = mMatch.NextMatch();
}
return aMatch;
}
static string GetFirstParagraph(string s)
{
Match m = Regex.Match(s, #"<p>\s*(.+?)\s*</p>");
if (m.Success)
{
return m.Groups[1].Value;
}
else
{
return "";
}
}
private String fetchText(String s)
{
//Filter out HTML and JavaScript from the page, leaving only body text
s = Convert.ToString(Regex.Match(s, #"<body.+?</body>", RegexOptions.Singleline | RegexOptions.IgnoreCase)); //strip everything but <BODY>
s = Regex.Replace(s, "<script[^>]*?>.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase); //strip JavaScript
s = Regex.Replace(s, "<[^>]*>", ""); //strip HTML tags
s = Regex.Replace(s, "&(copy|#169);|&(quot|#34);|&(amp|#38);|&(lt|#60);&(gt|#62);|&(nbsp|#160);|&(iexcl|#161);|&(cent|#162);|&(pound|#163);|ยท", " "); //strip symbols
s = s.Replace("\t", " "); //strip tabs
s = Regex.Replace(s, "([\r\n])+", " "); //strip carriage returns
s = Regex.Replace(s, "\\s\\s+", " "); //strip white space (must be last)
return s.Trim();
}
private String processURL(String sInput, String sURL)
{
sURL = "http://" + Convert.ToString(sURL.Split('/').GetValue(2));
if (sInput.IndexOf("http://") < 0)
{
if (!sInput.StartsWith("/") && !sURL.EndsWith("/"))
{
return sURL + "/" + sInput;
}
else
{
if (sInput.StartsWith("/") && sURL.EndsWith("/"))
{
return sURL.Substring(0, sURL.Length - 1) + sInput;
}
else
{
return sURL + sInput;
}
}
}
else
{
return sInput;
}
}
private bool checkFormat(String sURL)
{
//List only pages ending with valid extensions
String[] validExt = { ".html", ".php", ".asp", ".htm", ".jsp", ".shtml", ".php3", ".aspx", ".pl", ".cfm" };
sURL = Convert.ToString(sURL.Split('?').GetValue(0));
foreach (String ext in validExt)
{
if (sURL.Substring(sURL.Length - ext.Length, ext.Length).ToLower() == ext) { return true; }
}
return false;
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(label3.Text);
}
}
}
I do not see any attempts to call Alchemy API in your example but here's what you need to know:
Alchemy API uses standard Web Service calls with XML responses as default. However you can specify the response you want (JSON / RDP).
Here's the start-up documentation, Text Extraction and Requirements and URLGetText Endpoint (but check on the documentation website for the endpoint you need).
So my program works as it should. When I click the save button everything is saved to the database. However when I click the save button a second time it fails to work.Index was outside the bounds of the array. is the error in private void btnTest_click on line string Ullage = splitstring[2];
private void btnSave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\2014-06-26 TEK687 Config Tool\TEK687 Config Tool\bin\Debug\Results.mdb");
string SqlString = "insert into Table1 (PassOrFail,DateTested,TekNum,BatchNum,WeekNum,Serial,FirmwareVer,HardwareVer,TestPC,SettingsTest,Deleted,Ullage,SRC,Vbatt,Tamb,Ullage2,SRC2,Vbatt2,Tamb2) Values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("PassOrFail", txtPassFail.Text);
cmd.Parameters.AddWithValue("DateTested", txtDateTested.Text);
cmd.Parameters.AddWithValue("TekNum", txtTekPartNo.Text);
cmd.Parameters.AddWithValue("BatchNum", txtBatchNumber.Text);
cmd.Parameters.AddWithValue("WeekNum", txtWeekYearNo.Text);
cmd.Parameters.AddWithValue("Serial", txtSerialNumber.Text);
cmd.Parameters.AddWithValue("FirmwareVer", txtFirmwareVer.Text);
cmd.Parameters.AddWithValue("HardwareVer", txtHardwareVer.Text);
cmd.Parameters.AddWithValue("TestPC", txtTestPC.Text);
cmd.Parameters.AddWithValue("SettingsTest", cboSettingsProfiles.SelectedIndex);
cmd.Parameters.AddWithValue("Deleted", txtDeleted.Text);
cmd.Parameters.AddWithValue("Ullage", txtUllage1.Text);
cmd.Parameters.AddWithValue("SRC", txtSRC1.Text);
cmd.Parameters.AddWithValue("Vbatt", txtVbatt1.Text);
cmd.Parameters.AddWithValue("Tamb", txtTamb1.Text);
cmd.Parameters.AddWithValue("Ullage2", txtUllage2.Text);
cmd.Parameters.AddWithValue("SRC2", txtSRC2.Text);
cmd.Parameters.AddWithValue("Vbatt2", txtVbatt2.Text);
cmd.Parameters.AddWithValue("Tamb2", txtTamb2.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored successfully");
}
ClearTextBoxes(this);
}
Here is the code to add values to database error is at string Ullage = splitstring[2];
private void btnTest_Click(object sender, EventArgs e)
{
Cancel = false;
if (DiscoverDevice(false) == false)
{
MessageBox.Show("Error, device is not responding");
return;
}
string servo = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,S," + txtToolID.Text + ",30,\r\n", "\r\n", 4, ref servo, 500);
string test = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,T," + txtToolID.Text + "\r\n", "\r\n", 4, ref test, 500);
string[] splitstring = test.Split(',');
**string Ullage = splitstring[2];**
string SRC = splitstring[3];
string RSSI = splitstring[4];
string AlarmStatus = splitstring[5];
string RateofChange = splitstring[6];
string Tamb = splitstring[7];
string Vbatt = splitstring[8];
Ullage = Ullage.Replace("u:", "");
Tamb = Tamb.Replace("t:", "");
Vbatt = Vbatt.Replace("v:", "");
int Ull = Convert.ToInt32(Ullage);
int src = Convert.ToInt32(SRC);
int BV = Convert.ToInt32(Vbatt);
int temp = Convert.ToInt32(Tamb);
StringBuilder sb = new StringBuilder();
sb.Append(Ull);
txtUllage1.Text += sb.ToString();
StringBuilder sc = new StringBuilder();
sc.Append(src);
txtSRC1.Text += sc.ToString();
StringBuilder sd = new StringBuilder();
sd.Append(BV);
txtVbatt1.Text += sd.ToString();
StringBuilder se = new StringBuilder();
se.Append(temp);
txtTamb1.Text += se.ToString();
StringBuilder sm = new StringBuilder();
if ((Ull < 11) || (Ull > 13) || (src < 9) || (BV < 29))
{
txtPassFail.Text += "12cm FAIL";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
StringBuilder th = new StringBuilder();
th.Append("12cm FAIL");
txtResultsReading.Text += th.ToString();
}
string servoTwo = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,S," + txtToolID.Text + ",31,\r\n", "\r\n", 4, ref servoTwo, 500);
string tests = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,T," + txtToolID.Text + "\r\n", "\r\n", 4, ref tests, 500);
string[] splitstrings = tests.Split(',');
string Ullage2 = splitstrings[2];
string SRC2 = splitstrings[3];
string RSSI2 = splitstrings[4];
string AlarmStatus2 = splitstrings[5];
string RateofChange2 = splitstrings[6];
string Tamb2 = splitstrings[7];
string Vbatt2 = splitstrings[8];
Ullage2 = Ullage2.Replace("u:", "");
Tamb2 = Tamb2.Replace("t:", "");
Vbatt2 = Vbatt2.Replace("v:", "");
int Ull2 = Convert.ToInt32(Ullage2);
int src2 = Convert.ToInt32(SRC2);
int BV2 = Convert.ToInt32(Vbatt2);
int temp2 = Convert.ToInt32(Tamb2);
StringBuilder sf = new StringBuilder();
sf.Append(Ull2);
txtUllage2.Text += sf.ToString();
StringBuilder sg = new StringBuilder();
sg.Append(src2);
txtSRC2.Text += sg.ToString();
StringBuilder sh = new StringBuilder();
sh.Append(BV2);
txtVbatt2.Text += sh.ToString();
StringBuilder si = new StringBuilder();
si.Append(temp2);
txtTamb2.Text += si.ToString();
txtDateTested.Text = DateTime.Now.ToString();
txtTestPC.Text = System.Environment.UserName;
//boSettingsProfiles.Text= Settings.SettingsFile;
txtDeleted.Text = "CURRENT";
if ((Ull < 11) || (Ull > 13) || (src < 9) || (BV < 29))
{
txtPassFail.Text += " 3M FAIL";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
StringBuilder tg = new StringBuilder();
tg.Append(Environment.NewLine);
tg.Append("3M FAIL");
txtResultsReading.Text += tg.ToString();
}
else if ((Ull >= 11) && (Ull <= 13) && (src == 9) && (BV >= 29) &&
(Ull2 >= 11) && (Ull2 <= 13) && (src2 == 9) && (BV2 >= 29))
{
txtPassFail.Text += "PASS";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
txtResultsReading.Text += "PASS";
}
ReleaseDevice();//release the config tool after config is completed
}
}
Your splitstrings object doesn't have three objects in it, therefore you can't access the object at index 2. Therefore, you should implement a check to make sure it contains an object at that index before accessing, then handle the case where it doesn't as appropriate.
By the way, next time you ask a question about why something doesn't work, it's absolutely critical that you tell us about the exception you're getting, rather than making us ask for it. And you need to include the code that throws the exception. See How to create a Minimal, Complete, and Verifiable example.
Inspect the variable coming out of the WriteTextAndWaitForResponse call. It probably doesn't have 3 commas.
Here is some code i put together to search for numbers in a text file. It work's great for what i'm trying to do. right now it finds 7 locations and i need to read the lines at the 7 different indexes. what might be the best way to start this. Thanks, this is in C#.
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
using (OpenFileDialog dlgOpen = new OpenFileDialog())
{
//long count = 0; string line;
//bool start = false;
//string line;
List<String> LinesFound = new List<string>();
// Available file extensions
dlgOpen.Filter = "All files(*.*)|*.*";
// Initial directory
dlgOpen.InitialDirectory = "C://bin";
// OpenFileDialog title
dlgOpen.Title = "Load";
// Show OpenFileDialog box
if (dlgOpen.ShowDialog() == DialogResult.OK)
textBox1.Text = dlgOpen.FileName;
{
string str = System.IO.File.ReadAllText(dlgOpen.FileName);
Regex reg = new Regex("333333");
Match sat = reg.Match(str);
while (sat.Success)
{
richTextBox1.Text += (sat.Index + " "); //shows index where 333333 is
sat = reg.Match(str, sat.Index + sat.Length);
{
{
}
}
}
}
}
}
You can use ReadAllLines instead of ReadAllText, and match each line one by one, use a int[] variable to store all your matching line index.
var lines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "/files/file.txt");
Regex reg = new Regex("333333");
string str;
for(int i =1; i<lines.Length;i++)
{
str = lines[i];
Match sat = reg.Match(str);
if (sat.Success)
{
richTextBox1.Text += (i + 1 +" "); //shows index where 333333 is
}
}
I am creating a HTML to text parser. I need to remove all HTML elements and want to do a carriage return everytime there is a <BR> and then remove the <BR> as well after so there are no HTML tags left. I then want to parse the text for a certain string that is in the combobox. Thank you in advance for your help.
private void navigateWeb_Click(object sender, EventArgs e)
{
openFD.Title = "Select your configuration file";
openFD.InitialDirectory = "C:";
openFD.FileName = "";
openFD.Filter = "Config File (*.cfg)|*.cfg|Text File (*.txt)|*.txt|All Files (*.*)|*.*";
openFD.ShowDialog();
MyURL = openFD.FileName;
//Open and read file
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(MyURL);
richTextBox1.Text = objReader.ReadToEnd();
var lines = File.ReadAllLines(MyURL)
.Select(l => l.Trim())
.Where(l => l.StartsWith(comboBox1.Text));
textBox1.Text = String.Join(Environment.NewLine, lines);
}
*********UPDATE*****
Here is the solution that got the job done:
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);
}
private void navigateWeb_Click(object sender, EventArgs e)
{
openFD.Title = "Enter URL in the box below";
openFD.InitialDirectory = "C:";
openFD.FileName = "http://msnconf/configtc.aspx?IP=10.6.64.200&m=c";
openFD.Filter = "HTTP://|*.*|Config File (*.cfg)|*.cfg|Text File (*.txt)|*.txt|All Files (*.*)|*.*";
//openFD.ShowDialog();
if (openFD.ShowDialog() == DialogResult.Cancel)
{
//MessageBox.Show("cancel button clicked");
}
else
{
MyURL = openFD.FileName;
webBrowser1.Visible = true;
richTextBox1.Visible = false;
permitACL.Enabled = true;
//webBrowser1.Navigate(new Uri(MyURL.SelectedItem.ToString()));
webBrowser1.Navigate(MyURL);
//Open and read file
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(MyURL);
richTextBox1.Text = objReader.ReadToEnd();
//Read all lines of file
// String lines = objReader.ReadToEnd();
String[] crString = { "<BR> " };
String[] aLines = richTextBox1.Text.Split(crString, StringSplitOptions.RemoveEmptyEntries);
// String[] lines = File.ReadAllLines(MyURL);
String noHtml = String.Empty;
for (int x = 0; x < aLines.Length; x++)
{
if(permitACL.Checked)
{
if (aLines[x].Contains("permit"))
{
noHtml += (RemoveHTML(aLines[x]) + "\r\n");
}
}
if (aLines[x].Contains(comboBox1.Text))
{
noHtml += (RemoveHTML(aLines[x]) + "\r\n");
}
}
//Find lines that match our text in the combobox
//lines.Select(l => l.Trim());
//.Where(l => l.StartsWith(comboBox1.Text));
//Print results to textbox
textBox1.Text = String.Join(Environment.NewLine, noHtml);
}
}
I suggest you use the HTML Agility Pack - it is an HTML parser that you can query with using XPath syntax.
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);
}