Reading a specific value from a GitHub text file - c#

I would like to read from a text file in the Internet the certain assignment to a word.
In the output "content" I get the complete content of the text file.
But I only want v7.7.3 from the line: version = "v7.7.3".
How can I filter by version with the streamreader?
That is the LastVersion.txt file:
[general]
version = "v7.7.3"
messagenew = "Works with June 2018 Update!\n Plus new Smart Farm strategy\n New Siege Machines\n For more information, go to \n https://mybot.run \n Always free and open source."
messageold = "A new version of MyBot (v7.7.3) is available!\nPlease download the latest from:\nhttps://mybot.run"
Updated: That's my current code.
public string myBotNewVersionURL = "https://raw.githubusercontent.com/MyBotRun/MyBot/master/LastVersion.txt";
public string myBotDownloadURL = null;
public string userDownloadFolder = #"C:\Users\XXX\Download\";
public string newMyBotVersion = null;
public string currentMyBotVersion = null;
public string currentMyBotFileName = null;
public string currentMyBotPath = null;
public void Btn_checkUpdate_Click(object sender, EventArgs e)
{
OpenFileDialog openCurrentMyBot = new OpenFileDialog();
openCurrentMyBot.Title = "Choose MyBot.run.exe";
openCurrentMyBot.Filter = "Application file|*.exe";
openCurrentMyBot.InitialDirectory = userDownloadFolder;
if (openCurrentMyBot.ShowDialog() == DialogResult.OK)
{
MyBot_set.SetValue("mybot_path", Path.GetDirectoryName(openCurrentMyBot.FileName));
MyBot_set.SetValue("mybot_exe", Path.GetFullPath(openCurrentMyBot.FileName));
string latestMyBotPath = Path.GetFullPath(openCurrentMyBot.FileName);
var latestMyBotVersionInfo = FileVersionInfo.GetVersionInfo(latestMyBotPath);
currentMyBotVersion = "v" + latestMyBotVersionInfo.FileVersion;
MyBot_set.SetValue("mybot_version", currentMyBotVersion);
WebClient myBotNewVersionClient = new WebClient();
Stream stream = myBotNewVersionClient.OpenRead(myBotNewVersionURL);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
var sb = new StringBuilder(content.Length);
foreach (char i in content)
{
if (i == '\n')
{
sb.Append(Environment.NewLine);
}
else if (i != '\r' && i != '\t')
sb.Append(i);
}
content = sb.ToString();
var vals = content.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
)
.SkipWhile(line => !line.StartsWith("[general]"))
.Skip(1)
.Take(1)
.Select(line => new
{
Key = line.Substring(0, line.IndexOf('=')),
Value = line.Substring(line.IndexOf('=') + 1).Replace("\"", "").Replace(" ", "")
});
newMyBotVersion = vals.FirstOrDefault().Value;
}

Read From local
var vals = File.ReadLines("..\\..\\test.ini")
.SkipWhile(line => !line.StartsWith("[general]"))
.Skip(1)
.Take(1)
.Select(line => new
{
Key = line.Substring(0, line.IndexOf('=')),
Value = line.Substring(line.IndexOf('=') + 1)
});
Console.WriteLine("Key : " + vals.FirstOrDefault().Key +
" Value : " + vals.FirstOrDefault().Value);
Updated
for read from Git , File.ReadLines not work with URL.
string myBotNewVersionURL = "https://raw.githubusercontent.com/MyBotRun/MyBot/master/LastVersion.txt";
WebClient myBotNewVersionClient = new WebClient();
Stream stream = myBotNewVersionClient.OpenRead(myBotNewVersionURL);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
var sb = new StringBuilder(content.Length);
foreach (char i in content)
{
if (i == '\n')
{
sb.Append(Environment.NewLine);
}
else if (i != '\r' && i != '\t')
sb.Append(i);
}
content = sb.ToString();
var vals = content.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
)
.SkipWhile(line => !line.StartsWith("[general]"))
.Skip(1)
.Take(1)
.Select(line => new
{
Key = line.Substring(0, line.IndexOf('=')),
Value = line.Substring(line.IndexOf('=') + 1)
});
Console.WriteLine("Key : " + vals.FirstOrDefault().Key + " Value : " + vals.FirstOrDefault().Value);

Related

Thread in a web service doesn't start when called it from windows service

I have a windows service,the codes in that body are in a elapsed timer method. I call some web services in a loop,that those web services run in a thread.
I checked the services on servers, they dont start.
And when I take out the codes from thread body,those worked.
This is my windows service code that calls webservices from servers.
private void CallServiceForTrancoding(object sender, System.Timers.ElapsedEventArgs e)
{
DataSet.TranscodingVideosDataTable oTranscodingVideosDataTable = new DataSet.TranscodingVideosDataTable();
DataSetTableAdapters.TranscodingVideoTableAdapter oTranscodingVideoTableAdapter = new DataSetTableAdapters.TranscodingVideoTableAdapter();
oTranscodingVideoTableAdapter.FillVideosForTranscoding(oTranscodingVideosDataTable);
DataSet.ServersDataTable oServersDataTable = new DataSet.ServersDataTable();
DataSetTableAdapters.ServersTableAdapter oServersTableAdapter = new DataSetTableAdapters.ServersTableAdapter();
oServersTableAdapter.FillBaseOnConvertAction(oServersDataTable);
for (int i = 0; i < oTranscodingVideosDataTable.Count; i++)
{
if (oTranscodingVideosDataTable[i].IsQualityNull() == false)
{
var Qualities = oTranscodingVideosDataTable[i].Quality.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string path = oTranscodingVideosDataTable[i].Path + oTranscodingVideosDataTable[i].ObjectUniqueName;
string[] Url = new string[Qualities.Length];
for (int j = 0; j < Qualities.Length; j++)
{
if (j == 0)
{
Url[j] = path;
}
else
{
Url[j] = path.Replace(path.Split('/').Last(), "") + path.Split('/').Last().Split('.')[0] + "-" + Qualities[j] + "." + path.Split('/').Last().Split('.')[1];
}
}
string parameters = "Token=" + "#HelloWorld" +
"&Url=" + new JavaScriptSerializer().Serialize(Url) +
"&FileUniqueName=" + oTranscodingVideosDataTable[i].ObjectUniqueName +
"&ip=" + oTranscodingVideosDataTable[i].IPValid +
"&GregoreanDate=" + oTranscodingVideosDataTable[i].Gorean_Date.ToString();
DataSet.VideoDataTable oVideoDataTable = new DataSet.VideoDataTable();
DataSetTableAdapters.VideoTableAdapter oVideoTableAdapter = new DataSetTableAdapters.VideoTableAdapter();
oVideoTableAdapter.UpdateVideoStatus(oTranscodingVideosDataTable[i].ObjectUniqueName);
string WebServiceOfServer = oServersDataTable[i].WebService;
WebServiceOfServer = WebServiceOfServer.Replace(WebServiceOfServer.Split('/').Last(), "RS");
JavaScriptSerializer objSerializer = new JavaScriptSerializer();
//Task a = Task.Factory.StartNew(() => {
Task ResponseResult = GetPostMethods.POST(WebServiceOfServer, parameters);
string JSONResult = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ResponseResult);
var ResponseString = objSerializer.Deserialize<dynamic>(JSONResult);
var UserToken = ResponseString["Result"]["UserToken"];
var Successfully = ResponseString["Result"]["Successfully"];
//});
}
}
}
Here is my web method :
[WebMethod]
public void RS(string Token, string Url, string FileUniqueName, string ip,string GregoreanDate)
{
new Thread(() =>
{
if (Token != "HelloWorld")
{
}
else
{
try
{
var VideoUrl = new JavaScriptSerializer().Deserialize<string[]>(Url);
string[] FileName = new string[VideoUrl.Length];
string[] FilePath = new string[VideoUrl.Length];
t.VideoUniqueName = FileUniqueName.Split('.')[0];
t.mediaOutPath = HttpContext.Current.Server.MapPath("/video/") + DateTime.Parse(GregoreanDate).Year + "\\" + DateTime.Parse(GregoreanDate).Month + "\\" + FileUniqueName.Split('.')[0] + "\\";
t.mediaOutFolderPath = "/video/" + DateTime.Parse(GregoreanDate).Year + "/" + DateTime.Parse(GregoreanDate).Month + "/";
if (!Directory.Exists(t.mediaOutPath))
{
Directory.CreateDirectory(t.mediaOutPath);
Directory.CreateDirectory(t.mediaOutPath + "m3u8\\");
}
t.CreateFTPPathForVideoScheduler(t.VideoTypeFormKey, t.mediaOutPath);
string Paths = "";
for (int i = 0; i < VideoUrl.Length; i++)
{
FileName[i] = VideoUrl[i].Split('/').Last();
if (FileName[i] != FileUniqueName)
{
FilePath[i] = t.mediaOutPath + FileName[i];
}
else
{
FilePath[i] = t.ffmpegFolderPath + FileName[i];
}
using (WebClient client = new WebClientWithAwesomeTimeouts { Timeout = new TimeSpan(10, 0, 0, 0) })
{
try
{
client.DownloadFile(VideoUrl[i], FilePath[i]);
client.Dispose();
}
catch (Exception ex)
{
StreamWriter sw = new StreamWriter(t.LogPath, true);
sw.WriteLine(ex.Message + "----" + ex.StackTrace != null ? ex.StackTrace : "" + "----" + DateTime.Now);
sw.Close();
}
}
}
DirectoryInfo FilesDirectory = new DirectoryInfo(t.ffmpegFolderPath);
FileInfo[] fInfo = FilesDirectory.GetFiles("*" + FileUniqueName.Split('.')[0] + "*.*");
fInfo[0].CopyTo(t.mediaOutPath + FileUniqueName, true);
t.SendFileWithFTPScheduler(t.VideoTypeFormKey, t.mediaOutPath + FileUniqueName);
FilesDirectory = new DirectoryInfo(t.mediaOutPath);
fInfo = FilesDirectory.GetFiles("*" + FileUniqueName.Split('.')[0] + "*.*");
foreach (FileInfo file in fInfo)
{
t.SendFileWithFTPScheduler(t.VideoTypeFormKey, file.FullName);
}
string UniqueFilePath = FilePath[0].Replace(FilePath[0].Split('/').Last(), FileUniqueName);
JavaScriptSerializer objSerializer = new JavaScriptSerializer();
var VideoDimensions = objSerializer.Deserialize<Dictionary<string, string>>(t.getVideoHeightAndWidth(t.ffmpegFolderPath + UniqueFilePath));
string Width = VideoDimensions["Width"];
string Height = VideoDimensions["Height"];
Transcoding.VideoResolutions vr = new Transcoding.VideoResolutions();
var VideoResolutionsInfo = objSerializer.Deserialize<Dictionary<object, object>>(t.getVideoResolution(Height));
vr.OrginalResolution = VideoResolutionsInfo["OrginalResolution"].ToString();
vr.ResCount = Convert.ToInt32(VideoResolutionsInfo["ResCount"]);
vr.OrginalResIndex = Convert.ToInt32(VideoResolutionsInfo["OrginalResIndex"]);
vr.UpperResolutionHeight = VideoResolutionsInfo["UpperResolutionHeight"].ToString();
t.MakeM3U8FormatScheduler(FileUniqueName, vr.OrginalResolution, vr.ResCount, vr.OrginalResIndex, false, "", Height);
t.ProcessFilesScheduler(t.mediaOutPath + "m3u8\\", t.VideoTypeFormKey);
DataSet.VideoDataTable oVideoDataTable = new DataSet.VideoDataTable();
DataSetTableAdapters.VideoTableAdapter oVideoTableAdapter = new DataSetTableAdapters.VideoTableAdapter();
oVideoTableAdapter.UpdateVideoForAcceptation(1, true, "mp4,m3u8", "http://" + t.mediaOutFolderPath + t.VideoUniqueName + "/", FileUniqueName);
oVideoTableAdapter.UpdateStatus("resfinish", FileUniqueName);
foreach (string path in VideoUrl)
{
if (path.ToLower().Contains("mp4videos"))
{
t.FTPDelete(new Uri(path.Replace(new Uri(path).Host, ip).Replace("http", "ftp")));
}
}
System.IO.File.Delete(t.ffmpegFolderPath + UniqueFilePath);
System.IO.Directory.Delete(t.mediaOutPath, true);
}
catch (Exception ex)
{
}
}
}).Start();
}
Task ResponseResult = GetPostMethods.POST(WebServiceOfServer, parameters);
string JSONResult = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ResponseResult);
You are serializing a task. You surely want to wait for the result, don't you?
I debugged my web service and I found that the issue is related to httpcontext.current in thread is null .
For that I defined HttpContext.Current.Server.MapPath("/video/") as a variable in a class and I recalled it from the webservice.

Dynamic Table Loader

I have some files which I receive and don't know how many columns and rows I have in those files.
How can I make a generic loader with a generic model where I can always load the file but get different content?
I wrote this but know I know its not always the same table...
public override List<Object> getFile(string ab) {
if (ab == "A") {
ab = A;
} else {
ab = B;
}
List<FundPriceModel> models = new List<FundPriceModel>();
FileStream filestream = new FileStream(ab, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(filestream, Encoding.UTF8)) {
string line;
bool isHeader = true;
while ((line = reader.ReadLine()) != null) {
FundPriceModel model = new FundPriceModel();
if (isHeader) {
headers = line.Split(spliter[0]);
isHeader = false;
continue;
}
string[] attributes = line.Split(spliter);
model.LipperID = IfEmptyInt(attributes[0]);
model.PriceDate = IfEmptyDateTime(attributes[1]);
model.PriceCode = safeValue(attributes[2], v => v[0]);
model.PriceType = safeValue(attributes[3], v => v[0]);
model.PriceCurrency = safeValue(attributes[4], v => attributes[4]);
model.PriceValueLC = IfEmptyFloat(attributes[5]);
model.Estimate = safeValue(attributes[6], v => v[0]);
Console.WriteLine(model.LipperID + "\t" + model.PriceDate + "\t" + model.PriceCode + "\t" + model.PriceType +
"\t" + model.PriceCurrency + "\t" + model.PriceValueLC + "\t" + model.Estimate);
models.Add(model);
}
}
}
If a DataTable is generic enough you could use that, its not really a 'Model'. This code is not production worthy and only demonstrates how to load from a CSV.
private static void Main(string[] args)
{
string filePath = #"C:\temp\tesst.csv";
FileStream filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
DataTable inputTable = new DataTable();
using (StreamReader reader = new StreamReader(filestream, Encoding.UTF8))
{
//Get headers and add columns
string headers = reader.ReadLine();
foreach (var s in headers.Split(','))
{
inputTable.Columns.Add(s, typeof (string));
}
//Add rows
string line;
while ((line = reader.ReadLine()) != null)
{
int colIndex = 0;
DataRow dr = inputTable.NewRow();
foreach (var s in line.Split(','))
{
dr[colIndex] = s;
colIndex++;
}
inputTable.Rows.Add(dr);
}
}
}

Error , invalid Regular expression in c# console application

private static void PizzaHutPizzaScrapper()
{
try
{
MatchCollection mclName;
MatchCollection mclPrice;
WebClient webClient = new WebClient();
string strUrl = "http://www.pizzahut.com.pk/pizzas.html";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
Regex r = new Regex("(<p class=\"MenuDescHead\">[A-Za-z\\s*]+[0-9]*)");
// Regex r1 = new Regex("(<p class=\"MenuDescPrice\">[A-Za-z.\\s?]+[0-9]*[A-Za-z\\s?]*[0-9]*[A-Za-z.\\s?]*)");
Regex r1 = new Regex("(<p class=\"MenuDescPrice\">[0-9]*)");
mclName = r.Matches(pageContent);
mclPrice = r1.Matches(pageContent);
StringBuilder strBuilder = new StringBuilder();
string name = "";
string price = "";
List<string> menuPriceList = new List<string>();
foreach (Match ml in mclPrice)
{
price = ml.Value.Remove(0, ml.Value.IndexOf(">") + 1).Trim();
if (price != "")
{
menuPriceList.Add(ml.Value);
}
}
int j = 0;
for (int i = 0; i < mclName.Count; i++)
{
name = mclName[i].Value.Remove(0, mclName[i].Value.IndexOf(">") + 1);
if (i == 0 || i == 4)
{
price = menuPriceList[j].Remove(0, menuPriceList[j].IndexOf(">") + 1);
strBuilder.Append(name.Trim() + ", " + price.Trim() + " , PizzaHut\r\n");
j++;
}
price = menuPriceList[j].Remove(0, menuPriceList[j].IndexOf(">") + 1);
strBuilder.Append(name.Trim() + ", " + price.Trim() + " ,PizzaHut\r\n");
j++;
}`
i want to select numeric values only...but it fetch alphabets as well..
i want to select only numeric values from HTML and using [0-9]* as regular expression, but its not working and show alphabets as well. i want only numeric values, what is correct regular expression? any idea??
Here you go, what you're looking for are Grouping Constructs:
MatchCollection mclName;
MatchCollection mclPrice;
WebClient webClient = new WebClient();
string strUrl = "http://www.pizzahut.com.pk/pizzas.html";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
Regex nameRegex = new Regex("<p class=\"MenuDescHead\">([A-Za-z\\s]+[0-9]*)");
Regex priceRegex = new Regex("<p class=\"MenuDescPrice\">[^0-9]*([0-9]*)");
mclName = nameRegex.Matches(pageContent);
mclPrice = priceRegex.Matches(pageContent);
StringBuilder strBuilder = new StringBuilder();
List<string> menuPriceList = new List<string>();
foreach (Match ml in mclPrice)
{
string price = ml.Groups[1].ToString();
if (price != "" && price != "0")
{
menuPriceList.Add(price);
}
}
int j = 0;
for (int i = 0; i < mclName.Count; i++)
{
string price;
string name = mclName[i].Groups[1].ToString();
if (i == 0 || i == 4)
{
price = menuPriceList[j];
strBuilder.Append(name.Trim() + ", " + price.Trim() + " , PizzaHut\r\n");
j++;
}
price = menuPriceList[j];
strBuilder.Append(name.Trim() + ", " + price.Trim() + " ,PizzaHut\r\n");
j++;
}
Console.WriteLine(strBuilder.ToString());

Alternative to ReadLine?

I'm trying to read some files with ReadLine, but my file have some break lines that I need to catch (not all of them), and I don't know how to get them in the same array, neither in any other array with these separators... because... ReadLine reads lines, and break these lines, huh?
I can't replace these because I need to check it after the process, so I need to get the breaklines AND the content after that. That's the problem. How can I do that?
Here's my code:
public class ReadFile
{
string extension;
string filename;
System.IO.StreamReader sr;
public ReadFile(string arquivo, System.IO.StreamReader sr)
{
string ext = Path.GetExtension(arquivo);
sr = new StreamReader(arquivo, System.Text.Encoding.Default);
this.sr = sr;
this.extension = ext;
this.filename = Path.GetFileNameWithoutExtension(arquivo);
if (ext.Equals(".EXP", StringComparison.OrdinalIgnoreCase))
{
ReadEXP(arquivo);
}
else MessageBox.Show("Extensão de arquivo não suportada: "+ext);
}
public void ReadEXP(string arquivo)
{
string line = sr.ReadLine();
string[] words;
string[] Separators = new string[] { "<Segment>", "</Segment>", "<Source>", "</Source>", "<Target>", "</Target>" };
string ID = null;
string Source = null;
string Target = null;
DataBase db = new DataBase();
//db.CreateTable_EXP(filename);
db.CreateTable_EXP();
while ((line = sr.ReadLine()) != null)
{
try
{
if (line.Contains("<Segment>"))
{
ID = "";
words = line.Split(Separators, StringSplitOptions.None);
ID = words[0];
for (int i = 1; i < words.Length; i++ )
ID += words[i];
MessageBox.Show("Segment[" + words.Length + "]: " + ID);
}
if (line.Contains("<Source>"))
{
Source = "";
words = line.Split(Separators, StringSplitOptions.None);
Source = words[0];
for (int i = 1; i < words.Length; i++)
Source += words[i];
MessageBox.Show("Source[" + words.Length + "]: " + Source);
}
if (line.Contains("<Target>"))
{
Target = "";
words = line.Split(Separators, StringSplitOptions.None);
Target = words[0];
for (int i = 1; i < words.Length; i++)
Target += words[i];
MessageBox.Show("Target[" + words.Length + "]: " + Target);
db.PopulateTable_EXP(ID, Source, Target);
MessageBox.Show("ID: " + ID + "\nSource: " + Source + "\nTarget: " + Target);
}
}
catch (IndexOutOfRangeException e)
{
MessageBox.Show(e.Message.ToString());
MessageBox.Show("ID: " + ID + "\nSource: " + Source + "\nTarget: " + Target);
}
}
return;
}
If you are trying to read XML, try using the built in libaries, here is a simple example of loading a section of XML with <TopLevelTag> in it.
var xmlData = XDocument.Load(#"C:\folder\file.xml").Element("TopLevelTag");
if (xmlData == null) throw new Exception("Failed To Load XML");
Here is a tidy way to get content without it throwing an exception if missing from the XML.
var xmlBit = (string)xmlData.Element("SomeSubTag") ?? "";
If you really have to roll your own, then look at examples for CSV parsers,
where ReadBlock can be used to get the raw data including line breaks.
private char[] chunkBuffer = new char[4096];
var fileStream = new System.IO.StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
var chunkLength = fileStream.ReadBlock(chunkBuffer, 0, chunkBuffer.Length);

Remove all HTML tags and do a carriage return on <BR> in C#

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

Categories

Resources