C#: Searching for a keyword in a txt file - c#

I have a problem reading a comma-delimited TXT file. This is what I am trying to do. I'm searching a text file for a keyword and then, when I've found the line containing that keyword, getting the whole line of comma-delimited keywords into a string array. How can I do this?
Thanks

System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
String line;
String[] array;
while((line = file.ReadLine()) != null)
{
if (line.Contains("myString"))
{
array = line.Split(',');
}
}
file.Close();
In the if part yo can save your comma separated strings to an array

Basically, you're going to want to read the file line by line and check each of those lines for your string. When you find it, you'll take that line and split it into an array.
string temp = "";
string[] list;
IO.FileStream file = new IO.FileStream("MyFile.txt", IO.FileMode.Open);
IO.StreamReader reader = new IO.StreamReader(file);
While (!reader.EndOfStream)
{
temp = reader.ReadLine();
if (temp.Contains("myString")
{
list = temp.split(",");
break;
}
}
reader.close();

Related

Split file line by line into an array

I want to have an array based on the lines in the file, but at the moment its a fixed sized array:
string[] converList = new string[6]; // Array containing TXT lines
Reading the file:
void ReadConver()
{
string line;
int i = 0;
System.IO.StreamReader file =
new System.IO.StreamReader("C:\\Users\\Kennyist\\Documents\\Visual Studio 2010\\Projects\\soft140as3\\convert.txt");
while ((line = file.ReadLine()) != null)
{
converList[i] = line;
i++;
}
}
How would I do this?
You could create a list then use ToArray to make it into an array:
var cList = File.ReadAllLines("C:\\Users\\Kennyist\\Documents\\Visual Studio 2010\\Projects\\soft140as3\\convert.txt").ToList();
string[] converlist = clist.ToArray();
Also, use (#'C:\Kennyist...') instead of the double backslashes
Instead of doing things the hard way, you can just use:
var arrTextLines = File.ReadAllLines(#"C:\Users\Kennyist\Documents\Visual Studio 2010\Projects\soft140as3\convert.txt");
arrTextLines will be an object with the type string[].
Edited answer:
string[] converList;
System.IO.StreamReader file =
new System.IO.StreamReader("C:\\Users\\Kennyist\\Documents\\Visual Studio 2010\\Projects\\soft140as3\\convert.txt");
converList = new string[] { file.ReadToEnd() };
Thanks #Cole

MemoryStream to string[]

I read the content of a CSV file from a zip file in memory(the requirment is not to write to disk) into the MemoryStream. and use to following code to get the human readable string
string result = Encoding.ASCII.GetString(memoryStream.ToArray());
However, we would like the result to be a string[] to map each row in the CSV file.
Is there a way to handle this automatically?
Thanks
Firstly, there's no need to call ToArray on the memory stream. Just use a StreamReader, and call ReadLine() repeatedly:
memoryStream.Position = 0; // Rewind!
List<string> rows = new List<string>();
// Are you *sure* you want ASCII?
using (var reader = new StreamReader(memoryStream, Encoding.ASCII))
{
string line;
while ((line = reader.ReadLine()) != null)
{
rows.Add(line);
}
}
You can use Split method to split string by newlines:
string[] result = Encoding.
ASCII.
GetString(memoryStream.ToArray()).
Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Depending on the contents of your CSV file, this can be a much harder problem than you're giving it credit for.
assume this is your csv:
id, data1, data2
1, some data, more data
2, "This element has a new line
right in the middle of the field", and that can create problems if you're reading line by line
If you simply read this in line by line with reader.ReadLine(), you're not going to get what you want if you happen to have quoted fields with new lines in the middle (which is generally allowed in CSVs). you need something more like this
List<String> results = new List<string>();
StringBuilder nextRow = new StringBuilder();
bool inQuote = false;
char nextChar;
while(reader.ReadChar(out nextChar)){ // pretend ReadChar reads a char into nextChar and returns false when it hits EOF
if(nextChar == '"'){
inQuote = !inQuote;
} else if(!inQuote && nextChar == '\n'){
results.Add(nextRow.ToString());
nextRow.Length = 0;
} else{ nextString.Append(nextChar); }
}
note that this handles double quotes. Missing quotes will be a problem, but they always are in .csv files.

How to add lines of a text file into individual items on a ListBox (C#)

How would it be possible to read a text file with several lines, and then to put each line in the text file on a separate row in a ListBox?
The code I have so far:
richTextBox5.Text = File.ReadAllText("ignore.txt");
String text = File.ReadAllText("ignore.txt");
var result = Regex.Split(text, "\r\n|\r|\n");
foreach(string s in result)
{
lstBox.Items.Add(s);
}
string[] lines = System.IO.File.ReadAllLines(#"ignore.txt");
foreach (string line in lines)
{
listBox.Items.Add(line);
}
Write a helper method that return the collection of lines
static IEnumerable<string> ReadFromFile(string file)
{// check if file exist, null or empty string
string line;
using(var reader = File.OpenText(file))
{
while((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
use it
var lines = ReadFromFile(myfile);
myListBox.ItemsSource = lines.ToList(); // or change it to ObservableCollection. also you can add to the end line by line with myListBox.Items.Add()
You should use a streamreader to read the file one line at a time.
using (StreamReader sr = new StreamReader("ignore.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
listBox1.Items.Add(line);
}
StreamReader info -> http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
ListBox info -> http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.aspx

Parsing individual lines in a robots.txt file with C#

Working on an application to parse robots.txt. I wrote myself a method that pulled the the file from a webserver, and threw the ouput into a textbox. I would like the output to display a single line of text for every line thats in the file, just as it would appear if you were looking at the robots.txt normally, however the ouput in my textbox is all of the lines of text without carriage returns or line breaks. So I thought I'd be crafty, make a string[] for all the lines, make a foreach loop and all would be well. Alas that did not work, so then I thought I would try System.Enviornment.Newline, still not working. Here's the code as it sounds now....how can I change this so I get all the individual lines of robots.txt as opposed to a bunch of text cobbled together?
public void getRobots()
{
WebClient wClient = new WebClient();
string url = String.Format("http://{0}/robots.txt", urlBox.Text);
try
{
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
string[] lines = new string[] { read.ReadToEnd() };
foreach (string line in lines)
{
textBox1.AppendText(line + System.Environment.NewLine);
}
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, null, MessageBoxButtons.OK);
}
}
You are reading the entire file into the first element of the lines array:
string[] lines = new string[] {read.ReadToEnd()};
So all your loop is doing is adding the whole contents of the file into the TextBox, followed by a newline character. Replace that line with these:
string content = read.ReadToEnd();
string[] lines = content.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
And see if that works.
Edit: an alternative and perhaps more efficient way, as per Fish's comment below about reading line by line—replace the code within the try block with this:
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
while (read.Peek() >= 0)
{
textBox1.AppendText(read.ReadLine() + System.Environment.NewLine);
}
You need to make the textBox1 multiline. Then I think you can simply go
textBox1.Lines = lines;
but let me check that
Try
public void getRobots()
{
WebClient wClient = new WebClient();
string robotText;
string[] robotLines;
System.Text.StringBuilder robotStringBuilder;
robotText = wClient.DownloadString(String.Format("http://{0}/robots.txt", urlBox.Text));
robotLines = robotText.Split(Environment.NewLine);
robotStringBuilder = New StringBuilder();
foreach (string line in robotLines)
{
robotStringBuilder.Append(line);
robotStringBuilder.Append(Environment.NewLine);
}
textbox1.Text = robotStringBuilder.ToString();
}
Try using .Read() in a while loop instead of .ReadToEnd() - I think you're just getting the entire file as one line in your lines array. Debug and check the count of lines[] to verify this.
Edit: Here's a bit of sample code. Haven't tested it, but I think it should work OK;
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
List<string> lines = new List<string>();
string nextLine = read.ReadLine();
while (nextLine != null)
{
lines.Add(nextLine);
nextLine = read.ReadLine();
}
textBox1.Lines = lines.ToArray();

C# Cannot implicitly convert type 'string' to 'System.IO.StreamReader

What i'm trying to do is open every text file in a directory, read it line by line, and if it matches a specific content, do a regex and output it to a result. For some reason my text files ended up being in unicode...., not sure dont know why. So I was able to work around that but I cant work around the stream reader issue i'm having. If someone could suggest a way to work around this it would be great, and if that way is to convert those text files, so be it.
heres the code:
public void doSomeWork()
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Documents and Settings\123");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo filex in Files)
{
string line;
StreamReader sr = File.ReadAllText(filex.FullName, Encoding.Unicode);
StreamWriter sra = File.AppendText(#"C:\sharename.txt");
int counter = 0;
while((line = sr.ReadLine()) != null)
{
string matchingcontants = "Share";
if (line.Contains(matchingcontants))
{
string s = sr.ReadLine();
string sharename = Regex.Match(line, #"\+(\S*)(.)(.*)(.)").Groups[3].Value;
sra.WriteLine(sharename);
}
counter++;
}
sr.Close();
sra.Close();
}
File.ReadAllText actually reads the whole file into a string. Try File.OpenRead instead
File.ReadAllText returns a string containing all the text in the file.
Try changing:
StreamReader sr = File.ReadAllText(filex.FullName, Encoding.Unicode);
To
string[] lines = File.ReadAllLines(filex.FullName, Encoding.Unicode);
And changing
while((line = sr.ReadLine()) != null)
To
foreach(string line in lines)
And remove the following:
sr.Close();

Categories