Split string from text file - c#

I'm trying to convert string to keys from a text file and I need to split text.
For example:
Code c#
string[] controls = File.ReadAllLines(FilePath);
Keys move up = (Keys)Enum.Parse(type of(Keys),controls[1].Split("|", StringSplitOption.None), true);
In the text file at the line[1] I have :
moveUp |W;
I want to set the char W as keys.
Thanks to reply and sorry if my English looks weird.

If you are interested in string after | , then this should be:
controls[1].Split("|", StringSplitOption.None)
replaced with this:
controls[1].Split("|")[1]
[1] means return the 2nd index value from array which will be created by Split()
If you are trying to get from Line 1 then controls[1] should be controls[0] because arrays are zero index based.

Related

Search text file for text above which pattern matches input

I am trying to make my program display the text above the input text which matches a pattern I set.
For example, if user input 'FastModeIdleImmediateCount"=dword:00000000', I should get the closest HKEY above, which is [HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000] for this case.
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000]
"StandardModeIdleImmediateCount"=dword:00000000
"FastModeIdleImmediateCount"=dword:00000000
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD\DEVICE0]
"Attach.ToDesktop"=dword:00000001
Could anyone please show me how I can code something like that? I tried playing around with regular expressions to match text with bracket, but I am not sure how to make it to only search for the text above my input.
I'm assuming your file is a .txt file, although it's most probably not. But the logic is the same.
It is not hard at all, a simple for() loop would do the trick.
Code with the needed description:
string[] lines = File.ReadAllLines(#"d:\test.txt");//replace your directory. We're getting all lines from a text file.
string inputToSearchFor = "\"FastModeIdleImmediateCount\"=dword:00000000"; //that's the string to search for
int indexOfMatchingLine = Array.FindIndex(lines, line => line == inputToSearchFor); //getting the index of the line, which equals the matchcode
string nearestHotKey = String.Empty;
for(int i = indexOfMatchingLine; i >=0; i--) //looping for lines above the matched one to find the hotkey
{
if(lines[i].IndexOf("[HKEY_") == 0) //if we find a line which begins with "[HKEY_" (that means it's a hotkey, right?)
{
nearestHotKey = lines[i]; //we get the line into our hotkey string
break; //breaking the loop
}
}
if(nearestHotKey != String.Empty) //we have actually found a hotkey, so our string is not empty
{
//add code...
}
You could try to split the text into lines, find the index of the line that contains your text (whether exact match or regex is used doesn't matter) and then backsearch for the first key. Reverse sorting the lines first might help.

Read the Word File, identify headings,& get the content

I want to compare the heading of a word file with string, if it matches , then it displays it content
suppose a word file content 2-4 Paragraphs with heading, I want that it compare the heading with the string & display the content using C#
Not too sure how far you have gotten on the project, but this is how you can compare the heading to your selected string then display the header content.
char[] separ = new char[]{' '};
string[] yourSelectedHeaderText = YourString.Split(separ.StringSplitOptions.RemoveEmptyString)
string[] docHeader = HeaderSting.Split(separ,StringSplitOptions.RemoveEmptyString);
for(int i=0; i< docHeader.Length;i++){
if(docHeader[i] == yourSelectHeaderText[i]){
Console.WriteLine(docHeader[i].ToString());
}
}
Setting everything up into arrays or some kind of collection to iterate through is what you would want to do first, then I iterated through the header Strings one by one, under that iteration I added an if statement that would catch the matching header with your selected string. Inside the if statement we have the line that will display the string in your console.

grab value from string in reverse order

I have file with txt content inside. Content is generated dynamicly and I want to read in reverse order, from end of file to the first matched semicolon, for example:
sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456
so I want to grab this 123456 integer, ofcourse this is generated content with random int length.
If you have always the searched text at the end of the string and after a semicolon you could use
string.LastIndexOf(';');
for example
string test = "sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456";
int pos = test.LastIndexOf(';');
if(pos >= 0)
string myText = test.Substring(pos+1);
What #Steve said, or just
string value = "sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456";
string number = value.Split(';')[1];
though this doesn't handle the case where a semi-colon is missing.

how to find indexof substring in a text file

I have converted an asp.net c# project to framework 3.5 using VS 2008. Purpose of app is to parse a text file containing many rows of like information then inserting the data into a database.
I didn't write original app but developer used substring() to fetch individual fields because they always begin at the same position.
My question is:
What is best way to find the index of substring in text file without having to manually count the position? Does someone have preferred method they use to find position of characters in a text file?
I would say IndexOf() / IndexOfAny() together with Substring(). Alternatively, regular expressions. It the file has an XML-like structure, this.
If the files are delimited eg with commas you can use string.Split
If data is: string[] text = { "1, apple", "2, orange", "3, lemon" };
private void button1_Click(object sender, EventArgs e)
{
string[] lines = this.textBoxIn.Lines;
List<Fruit> fields = new List<Fruit>();
foreach(string s in lines)
{
char[] delim = {','};
string[] fruitData = s.Split(delim);
Fruit f = new Fruit();
int tmpid = 0;
Int32.TryParse(fruitData[0], out tmpid);
f.id = tmpid;
f.name = fruitData[1];
fields.Add(f);
}
this.textBoxOut.Clear();
string text=string.Empty;
foreach(Fruit item in fields)
{
text += item.ToString() + " \n";
}
this.textBoxOut.Text = text;
}
}
The text file I'm reading does not contain delimiters - sometimes there spaces between fields and sometimes they run together. In either case, every line is formatted the same. When I asked the question I was looking at the file in notepad.
Question was: how do you find the position in a file so that position (a number) could be specified as the startIndex of my substring function?
Answer: I've found that opening the text file in notepad++ will display the column # and line count of any position where the curser is in the file and makes this job easier.
You can use indexOf() and then use Length() as the second substring parameter
substr = str.substring(str.IndexOf("."), str.Length - str.IndexOf("."));

searching a textfile for a keyword

I have a text file with names as balamurugan,chendurpandian,......
if i give a value in the textbox as ba ....
If i click a submit button means i have to search the textfile for the value ba and display as pattern matched....
I have read the text file using
string FilePath = txtBoxInput.Text;
and displayed it in a textbox using
textBoxContents.Text = File.ReadAllText(FilePath);
But i dont know how to search a word in a text file using c# can anyone give suggestion???
You can simply use:
textBoxContents.Text.Contains(keyword)
This will return true if your text contains your chosen keyword.
Depends upon the kind of pattern matching that you needs - you can use as simple as String.Contains method or can try out Regular Expressions that will give you more control on how you want to search and give all matches at the same time. Here are couple of links to get you started quickly on regular expressions:
http://www.codeproject.com/KB/dotnet/regextutorial.aspx
http://www.developer.com/open/article.php/3330231/Regular-Expressions-Primer.htm
First, you should split up the input string, after which you could do a contains on each value:
// On file read:
String[] values = File.ReadAllText(FilePath);
// On search:
List<String> results = new List<String>();
for(int i = 0; i < values.Length; i++) {
if(values[i].Contains(search)) results.Add(values[i]);
}
Alternatively, if you only want it to search at the beginning or the end of the string, you can use StartsWith or EndsWith, respectively:
// Only match beginnging
values[i].StartsWith(search);
// Only match end
values[i].EndsWith(search);

Categories