I tried to find a solution for this question, but with no success...
I tried to remove .ToString() from Request.QueryString[var] and to add an if control
at the beginning like this
if Request.QueryString.HasKeys()) {
foreach (string var in Request.QueryString)
{.........
.............
}
but nothing....
The complete code is
string[] array_split_item = new string[] {"<script", "</script>", "‘", "’" };
int pos = 0;
string strReq = "";
foreach (string var in Request.QueryString)
{
foreach (string strItem in array_split_item)
{
strReq = Request.QueryString[var].ToString();
pos = strReq.ToLower().IndexOf(strItem.ToLower()) + 1;
if (pos > 0)
{
Response.Write("Some Text");
Response.End();
}
}
}
Why this exception?
Thanks
you can't foreach through Request.QueryString like that.
Try this (not tested)
foreach (string KEY in Request.QueryString.Keys)
{
string value = Request.QueryString[KEY]; //already a string by design, no need to ToString() it
// ... use value for whatever you need
}
EDIT:
visual studio 2008 builds this fine (pasted into the page_load method of an ASPX page to try it); Visual Studio 2010 SP1 doesn't complain either upoon building.
string[] array_split_item = new string[] { "<script", "</script>", "‘", "’" };
int pos = 0;
string strReq = "";
foreach (string var in Request.QueryString.Keys)
{
foreach (string strItem in array_split_item)
{
strReq = Request.QueryString[var].ToString();
pos = strReq.ToLower().IndexOf(strItem.ToLower()) + 1;
if (pos > 0)
{
Response.Write("Some Text");
Response.End();
}
}
}
There must be something wrong somewhere else in the code i think.
I beleive it may be because you're using the value of a key in QueryString to access a value.
Try changing the line strReq = Request.QueryString[var].ToString(); to
strReq = var.ToString();
You should use Request.QueryString.Keys to loop on the QueryString:
foreach (string key in Request.QueryString.Keys)
{
string value = Request.QueryString[key];
if (!String.IsNullOrEmpty(value))
{
//do work
}
}
You are naming your string var which is also a type. Replace var with another name.
foreach (string text in Request.QueryString.Keys)
.....
strReq = Request.QueryString[text].ToString();
Related
For each of the lines with the specific keyword, I want to print it to a TextBox.
But once I got it to read the text file and select the lines with the keyword and add it to a List, it only displays the first line of the list.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var client = new WebClient();
var text = client.DownloadString("https://foo.com/list");
File.WriteAllText("C:/ProgramData/oof.txt", text);
string searchKeyword = "Name";
string fileName = "C:/ProgramData/oof.txt";
string[] textLines = File.ReadAllLines(fileName);
List<string> results = new List<string>();
foreach (string line in textLines)
{
if (line.Contains(searchKeyword))
{
results.Add(line);
}
foreach (var item in results)
{
richTextBox1.Text = item;
}
}
}
your loop at the end just sets the text to the last item.
foreach (var item in results)
{
richTextBox1.Text = item;
}
not clear what you want but how about this.
var sb = new StringBuilder();
foreach (var item in results)
{
sb.Append(item);
sb.Append " ";
}
richTextBox1.Text = sb.ToString();
Given text file which contains the registration data like a database:
[ID] [Uname] [PW] [Email]
0 Aron asd asd#mail.com
1 Aron2 asdd asd#mail.com
I have the username and the password input.
How would i read only that line in this text file where my uname.Text and password.Text are given?
I agree with all the comments above. With the hypothesis that the file is not huge, you can simply load it all in memory and work on it:
//Load your files in a list of strings
IList<string> lines = File.ReadLines("\path\to\your\file.txt");
//Filter the list with only the pattern you want
var pattern = username + "[ ]{1,}" + password;
Regex regex = new Regex(pattern);
IList<string> results = lines.Where(x => regex.IsMatch(x)).ToList();
Here's a .NET fiddler that shows this.
If anyone have this problem too, this is my solve:
int check=0;
if (txt_uname.Text != "")
{
check = 0;
System.IO.StreamReader file = new System.IO.StreamReader(path);
string[] columnnames = file.ReadLine().Split('\t');
string newline;
while ((newline=file.ReadLine()) != null)
{
string[] values = newline.Split('\t');
if (check== 0){
for (int i = 0; i < values.Length; i++)
{
if (txt_uname.Text == values[i] && txt_pw.Text == values[i + 1])
{
Console.WriteLine("User found");
check= 1;
break;
}
else
{
Console.WriteLine("User isn't exists");
}
}
}
}
Try this:
var username = "Aron2";
var password = "asdd";
List<string> matchedValues; // Contains field values of matched line.
var lines = File.ReadLines("input.txt");
foreach (string l in lines)
{
var values = l.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
if (values.Contains(username) && values.Contains(password))
{
matchedValues = values;
break; // Matching line found. No need to loop further.
}
}
I have a list of words. I want the program to scan for multiple words from a text file.
This is what i already have:
int counter = 0;
string line;
StringBuilder sb = new StringBuilder();
string[] words = { "var", "bob", "for", "example"};
try
{
using (StreamReader file = new StreamReader("test.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(Convert.ToChar(words)))
{
sb.AppendLine(line.ToString());
}
}
}
listResults.Text += sb.ToString();
}
catch (Exception ex)
{
listResults.ForeColor = Color.Red;
listResults.Text = "---ERROR---";
}
So i want to scan the file for a word, and if it's not there, scan for the next word...
String.Contains() only takes one argument: a string. What your call to Contains(Convert.ToChar(words)) does, is probably not what you expect.
As explained in Using C# to check if string contains a string in string array, you might want to do something like this:
using (StreamReader file = new StreamReader("test.txt"))
{
while ((line = file.ReadLine()) != null)
{
foreach (string word in words)
{
if (line.Contains(word))
{
sb.AppendLine(line);
}
}
}
}
Or if you want to follow your exact problem statement ("scan the file for a word, and if it's not there, scan for the next word"), you might want to take a look at Return StreamReader to Beginning:
using (StreamReader file = new StreamReader("test.txt"))
{
foreach (string word in words)
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(word))
{
sb.AppendLine(line);
}
}
if (sb.Length == 0)
{
// Rewind file to prepare for next word
file.Position = 0;
file.DiscardBufferedData();
}
else
{
return sb.ToString();
}
}
}
But this will think "bob" is part of "bobcat". If you don't agree, see String compare C# - whole word match, and replace:
line.Contains(word)
with
string wordWithBoundaries = "\\b" + word + "\\b";
Regex.IsMatch(line, wordWithBoundaries);
StringBuilder sb = new StringBuilder();
string[] words = { "var", "bob", "for", "example" };
string[] file_lines = File.ReadAllLines("filepath");
for (int i = 0; i < file_lines.Length; i++)
{
string[] split_words = file_lines[i].Split(' ');
foreach (string str in split_words)
{
foreach (string word in words)
{
if (str == word)
{
sb.AppendLine(file_lines[i]);
}
}
}
}
This works a treat:
var query =
from line in System.IO.File.ReadLines("test.txt")
where words.Any(word => line.Contains(word))
select line;
To get these out as a single string, just do this:
var results = String.Join(Environment.NewLine, query);
Couldn't be much simpler.
If you want to match only whole words it becomes only a little more complicated. You can do this:
Regex[] regexs =
words
.Select(word => new Regex(String.Format(#"\b{0}\b", Regex.Escape(word))))
.ToArray();
var query =
from line in System.IO.File.ReadLines(fileName)
where regexs.Any(regex => regex.IsMatch(line))
select line;
I have a string as in the following format:
"one,",2,3,"four " ","five"
I need output in the following format:
one,
2
3
four "
five
Can anyone help me to create Regex for the above?
You can do this without Regex. It's not clear to me, what you're trying to do though. I've adjusted the code for the updated question:
var text = "\"one\",2,3,\"four \"\",\"five\"";
var collection = text
.Split(',')
.Select(s =>
{
if (s.StartsWith("\"") && s.EndsWith("\""))
{
s = s.Substring(1, s.Length - 2);
}
return s;
})
.ToList();
foreach (var item in collection)
{
Console.WriteLine(item);
}
I've added another sample for you, which uses a CSV reader. I've installed the "CsvHelper" package from NuGet:
const string text = "\"one,\",2,3,\"four \"\"\",\"five\"";
using (var textReader = new StringReader(text))
using (var reader = new CsvReader(textReader))
{
reader.Configuration.Delimiter = ',';
reader.Configuration.AllowComments = false;
reader.Configuration.HasHeaderRecord = false;
if (reader.Read())
{
foreach (var item in reader.CurrentRecord)
{
Console.WriteLine(item);
}
}
}
string newString = Regex.Replace(oldString, #'[^",]', ' ');
I hope the regular expression is good, but I just want you you to see the idea.
EDIT:
string newString = Regex.Replace(oldString, #'[^",]', '\n');
I post the complete code below, so you can see what I'm doing.
Situation:
I create a IHTMLDocument2 currentDoc pointing to the DomDocument
I write the proper string
I close the currentDoc
program shows me the html code including the CSS stuff 100% correct. Works
Now I want to change the CSS, instead of 2 columns I set it to 3 columns
(Simply change the width:48% to width:33%)
and rerun the code with the new 33%
now it suddenly doesn't apply any CSS style anymore.
When I close the program, and then change the CSS to 33% again, it works flawless
So, somehow, without disposing the complete webbrowser, I can't load the CSS a 2nd time..
or, the first CSS is somewhere in some cache, and conflicts with the 2nd CSS.. Just riddling here.. really need help on how to solve this
I searched the internet and stackoverflow long enough that I need to post this, even if someone else on this planet already posted it somewhere, I didn't find it.
private void doWebBrowserPreview()
{
if (lMediaFiles.Count == 0)
{
return;
}
Int32 iIndex = 0;
for (iIndex = 0; iIndex < lMediaFiles.Count; iIndex++)
{
if (!lMediaFiles[iIndex].isCorrupt())
{
break;
}
}
String strPreview = String.Empty;
String strLine = String.Empty;
// Set example Media
String strLinkHTM = lMediaFiles[iIndex].getFilePath();
FileInfo movFile = new FileInfo(strLinkHTM + lMediaFiles[iIndex].getFileMOV());
String str_sizeMB = (movFile.Length / 1048576).ToString();
if (str_sizeMB.Length > 3)
{
str_sizeMB.Insert(str_sizeMB.Length - 3, ".");
}
//Get info about our media files
MediaInfo MI = new MediaInfo();
MI.Open(strLinkHTM + lMediaFiles[iIndex].getFileM4V());
String str_m4vDuration = // MI.Get(0, 0, 80);
MI.Get(StreamKind.Video, 0, 74);
str_m4vDuration = "Duration: " + str_m4vDuration.Substring(0, 8) + " - Hours:Minutes:Seconds";
String str_m4vHeightPixel = MI.Get(StreamKind.Video, 0, "Height"); // "Height (Pixel): " +
Int32 i_32m4vHeightPixel;
Int32.TryParse(str_m4vHeightPixel, out i_32m4vHeightPixel);
i_32m4vHeightPixel += 16; // for the quicktime embed menu
str_m4vHeightPixel = i_32m4vHeightPixel.ToString();
String str_m4vWidthPixel = MI.Get(StreamKind.Video, 0, "Width"); //"Width (Pixel): " +
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_header")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strLine = xmlLineDes.Value;
strLine = strLine.Replace(#"%date%", lMediaFiles[iIndex].getDay().ToString() + " " + lMediaFiles[iIndex].getMonth(lMediaFiles[iIndex].getMonth()) + " " + lMediaFiles[iIndex].getYear().ToString());
strPreview += strLine + "\n";
}
}
}
}
}
strLine = "<style type=\"text/css\">" + "\n";
foreach (XElement xmlLine in s.getTemplates().getLayoutCSS().Element("layoutCSS").Elements("layout"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "layoutMedia")
{
foreach (XElement xmlLineDes in xmlLine.Elements("layout"))
{
var queryL = xmlLineDes.Attributes("type");
foreach (XAttribute resultL in queryL)
{
if (resultL.Value == "layoutVideoBox")
{
foreach (XElement xmlLineDesL in xmlLineDes.Descendants())
{
if (xmlLineDesL.Name == "dataline")
{
strLine += xmlLineDesL.Value + "\n";
}
}
}
}
}
}
}
}
strLine += "</style>" + "\n";
strPreview = strPreview.Insert(strPreview.LastIndexOf("</head>", StringComparison.Ordinal), strLine);
for (Int16 i16Loop = 0; i16Loop < 3; i16Loop++)
{
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_videolist")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strLine = xmlLineDes.Value;
strLine = strLine.Replace(#"%m4vfile%", strLinkHTM + lMediaFiles[iIndex].getFileM4V());
strLine = strLine.Replace(#"%moviefile%", strLinkHTM + lMediaFiles[iIndex].getFileMOV());
strLine = strLine.Replace(#"%height%", str_m4vHeightPixel);
strLine = strLine.Replace(#"%width%", str_m4vWidthPixel);
strLine = strLine.Replace(#"%duration%", str_m4vDuration);
strLine = strLine.Replace(#"%sizeMB%", str_sizeMB);
strLine = strLine.Replace(#"%date%", lMediaFiles[iIndex].getDay().ToString() + " " + lMediaFiles[iIndex].getMonth(lMediaFiles[iIndex].getMonth()) + " " + lMediaFiles[iIndex].getYear().ToString());
strPreview += strLine + "\n";
}
}
}
}
}
}
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_footer")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strPreview += xmlLineDes.Value + "\n";
}
}
}
}
}
webBrowserPreview.Navigate("about:blank");
webBrowserPreview.Document.OpenNew(false);
mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowserPreview.Document.DomDocument;
currentDoc.clear();
currentDoc.write(strPreview);
currentDoc.close();
/*
try
{
if (webBrowserPreview.Document != null)
{
IHTMLDocument2 currentDocument = (IHTMLDocument2)webBrowserPreview.Document.DomDocument;
int length = currentDocument.styleSheets.length;
IHTMLStyleSheet styleSheet = currentDocument.createStyleSheet(#"", 0);
//length = currentDocument.styleSheets.length;
//styleSheet.addRule("body", "background-color:blue");
strLine = String.Empty;
foreach (XElement xmlLine in s.getTemplates().getLayoutCSS().Element("layoutCSS").Elements("layout"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "layoutMedia")
{
foreach (XElement xmlLineDes in xmlLine.Elements("layout"))
{
var queryL = xmlLineDes.Attributes("type");
foreach (XAttribute resultL in queryL)
{
if (resultL.Value == "layoutVideoBox")
{
foreach (XElement xmlLineDesL in xmlLineDes.Descendants())
{
if (xmlLineDesL.Name == "dataline")
{
strLine += xmlLineDesL.Value;
}
}
}
}
}
}
}
}
//TextReader reader = new StreamReader(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "basic.css"));
//string style = reader.ReadToEnd();
styleSheet.cssText = strLine;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}*/
webBrowserPreview.Refresh();
}
I now successfully implemented the berkelium-sharp method to my project
Has the same bug!
Found a solution!
First attempt which didn't work:
I had a persistent form (main form) and inside it a nested WebBrowser.
After changing the html with it's css, i told it to navigate to this new html!
This didn't work either:
Then I tried putting webbrowser on an own form. Which I simply open/close each
time I need a refresh. TO be sure the garbage collector cleans everything
Then I tried the Berkelium and rewrote it to my needs:
same logic as attempt 2 with the webbrowser. No luck either.
So I tried to open firefox itself and see if I can emulate this behaviour with a real browser. Indeed! When I open firefox, and force open the file (if you simply open a new file, firefox doesn't actually navigate to it, but detects this was already opened and simply refreshes it)
I noticed this due to the fast opening of the page!
A little scripting to force opening the same file twice (navigating) in 1 firefox session had the same effect: all CSS corrupt!
so, for some reason, you shouldn't navigate the same file twice, but instead of closing anything, simply force a refresh! Not a "Navigate"
Hope this info can help others, since I lost a lot of time finding out that it is the "navigate" to the same file more then once causing the corruption of stylesheets