reading lines in c# with a "condition" - c#

i've got a little question..
i have a simple txt file with some lines in it, but i struggle with something :
the text file is linked to 3 methods by example :
method 1 calls : "callMath", 2: "callFrench" and 3: "callDutch".
the text file looks like this by example:
math_tafels_question1
dutch_dt_question1
french_vocab_question1
math_tafels_question2
dutch_dt_question2
french_vocab_question2
etc etc..
my question is is there something like a substring command or something that if i call the method "callMath" that it only reads the lines that start with "math?" and if i call the method "callFrench" it only reads the lines that start with "french"?
you may say sort them and read them per 10 or something, but the thing is some questions will be deleted, and there will be some questions added, so i never know the exact line number of the questions..
hope anyone can help me out?;)

That doesn't look like a very well-thought out file format, but I guess you'll have to live with it.
It's trivial what you want to do though:
var relevantLines = File.ReadLines(filename)
.Where(l => l.StartsWith("math_"));
This will give you an IEnumerable<string> with all lines from filename that start with "math_".
See also What's the fastest way to read a text file line-by-line?, How to check if a word starts with a given character?.

You're probably looking for the StartsWith() method. Here's how you could use that in your scenario:
using (var reader = new System.IO.StreamReader(#"C:\yourfile.txt"))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.StartsWith("math_"))
{
// do something
}
}
reader.Close();
}
You can then put the matching lines in an array and return them in your callMath() method or something like that.

Related

c# Is there a way to write code inside of program.cs?

Ok i might sound really stupid here but. I have a list, lets call it example
List<string> example = new List<string>();
example.Add("abc123");
//...
and everytime the user runs the program it detects an input
string input = Console.ReadLine();
and i want it so that if it detects something new that isnt in the list it will add it to the list.
or is there a workaround like putting the words in a different txt file and it can just write it onto said file and putting it on the list.
Thanks in advance.
For those of you who has encountered the same problem as mine. You could just put the items you want to put in your list to a different txt file. and then
string example = Console.ReadLine();
string savedExample = Environment.NewLine + example;
List<string> exampleList = File.ReadAllLines("listOfItems.txt").ToList();
and to add your item into the list
File.AppendAllText(#"listOfItems.txt", savedExample);
It will add example into the list which is the users input.
The Environment.NewLine is to add a new line so the program wont just keep writing on the same line
Note: the listOfItems.txt is expected to be in the same file path as your program.cs or simply you can replace it with a path
(edit because i forgot to mention): make sure your listOfItems.txt is something like
hello
abc123
test
example
//and so on
and not something like
exampleList.Add("hello");
exampleList.Add("abc123");
//...

Click a listbox item and display textfile text in labels

I'm getting stuck clicking a listbox item (the items in my listbox is .txt files in a folder) and displaying the values in the .txt file.
the values in the .txt files are all seperated with a "," and I want each Split item to display in labels on my form.
my file path is: System.AppDomain.CurrentDomain.BaseDirectory + "data"
my .txt file names are the names of the selected item in my listbox.
I have a basic idea of what should happen, but I have no clue how to express this in code.
My Code:
private void custList_MouseClick(object sender, MouseEventArgs e)
{
string foldr = System.AppDomain.CurrentDomain.BaseDirectory + "data";
string file = custList.SelectedIndex.ToString();
}
Thanx in advance
Before i go on answering this question, please read How to ask. This will help you better understand this community and ask better questions(to get better support).
Next on, do some research. From a first glance, it looks like you are asking someone to do the homework for you. Anyways, i am not here to be tough on you. I will point you out a few things. Try to understand them and utilize them.
Note that even though it may seem as such but i am not a fan of spoon-feeding so be sincere and do your research.
Let's start with your text file. As you mentioned, it contains values. C#, being a versatile & mature language has a lot of functions,methods,classes pre-built to help boost your programming experience. Such a method is ReadAllText, a part of the File class. In the simplest words, this method opens a text file, reads it, returns it's value. A sample use of this method could be :
string TextFromFile = File.ReadAllText(File_Path_Goes_Here);
Moving on... Your text file has multiple values separated by comma(,). In such cases, each value needs to read as a separate value upon retrieving or displaying. So, you want a List of the values, end of story. In C#, you have a wide range of generic lists to use from. As the values in the text file are simple strings, you can use a List<string> in this regard. A basic usage example of List<string> would be :
List<string> TestList1 = new List<string>();
TestList1.Add("First Value"); TestList1.Add("Second Value");
///or
List<string> TestList1 = new List<string>(){ "First Value", "Second Value" };
In your particular case, File.ReadAllLines is worth an example. The method opens a text file, reads it, closes it. Of course it returns the value read from the text file, as an array. So, when passing values to the generic list, you can simply make use of this method. Example :
...... new List<string>(File.ReadAllLines(Path_Of_File_Goes_Here));
The only twist here is that the values in your text file are in a line(maybe) and also are separated by comma. So, what do you think should work here ? ReadAllText or ReadAllLines ? I will leave it upto you.
Once values are read from the file, we can make use of the Split function to split the values upon each occurrence of a comma(,). A simple example :
List<string> NameList = "Josh,Riley".Split(',').ToList<string>();
And last but not the least, the headline of the question which doesn't seem to have anything to do with the post itself, here's what you can take a look at :
Control Click Event
ListBox.GetItemText
Tip: The SelectedItem property of the ListBox class returns or sets the selected item of a listbox.
I hope this has been helpful. Do pay attention to all that's mentioned above. It may be a bit hard to follow up with at first, but remember, Consistency is the hallmark of the unimaginative.
....Yeah, that's not my quote. Gotcha!
I don't know where you want to show the values of your text file, so I will just provide you what you need to retrieve those informations.
To get values from your file:
public string[] GetValues()
{
string[] values;
using(StreamReader sr = new StreamReader(Path.Combine(foldr, file))
{
string text = sr.ReadToEnd();
values = text.Split(',');
}
return values;
}
Then you can show them using an array:
public void Main()
{
string[] values = GetValues();
foreach(var value in values)
{
Console.WriteLine(value);
}
}
Hope this helps.

Replacing a word in a text file

I'm doing a little program where the data saved on some users are stored in a text file. I'm using Sytem.IO with the Streamwriter to write new information to my text file.
The text in the file is formatted like so :
name1, 1000, 387
name2, 2500, 144
... and so on. I'm using infos = line.Split(',') to return the different values into an array that is more useful for searching purposes. What I'm doing is using a While loop to search for the correct line (where the name match) and I return the number of points by using infos[1].
I'd like to modify this infos[1] value and set it to something else. I'm trying to find a way to replace a word in C# but I can't find a good way to do it. From what I've read there is no way to replace a single word, you have to rewrite the complete file.
Is there a way to delete a line completely, so that I could rewrite it at the end of the text file and not have to worried about it being duplicated?
I tried using the Replace keyword, but it didn't work. I'm a bit lost by looking at the answers proposed for similar problems, so I would really appreciate if someone could explain me what my options are.
If I understand you correctly, you can use File.ReadLines method and LINQ to accomplish this.First, get the line you want:
var line = File.ReadLines("path")
.FirstOrDefault(x => x.StartsWith("name1 or whatever"));
if(line != null)
{
/* change the line */
}
Then write the new line to your file excluding the old line:
var lines = File.ReadLines("path")
.Where(x => !x.StartsWith("name1 or whatever"));
var newLines = lines.Concat(new [] { line });
File.WriteAllLines("path", newLines);
The concept you are looking for is called 'RandomAccess' for file reading/writing. Most of the easy-to-use I/O methods in C# are 'SequentialAccess', meaning you read a chunk or a line and move forward to the next.
However, what you want to do is possible, but you need to read some tutorials on file streams. Here is a related SO question. .NET C# - Random access in text files - no easy way?
You are probably either reading the whole file, or reading it line-for-line as part of your search. If your fields are fixed length, you can read a fixed number of bytes, keep track of the Stream.Position as you read, know how many characters you are going to read and need to replace, and then open the file for writing, move to that exact position in the stream, and write the new value.
It's a bit complex if you are new to streams. If your file is not huge, copying a file line for line can be done pretty efficiently by the System.IO library if coded correctly, so you might just follow your second suggestion which is read the file line-for-line, write it to a new Stream (memory, temp file, whatever), replace the line in question when you get to that value, and when done, replace the original.
It is most likely you are new to C# and don't realize the strings are immutable (a fancy way of saying you can't change them). You can only get new strings from modifying the old:
String MyString = "abc 123 xyz";
MyString.Replace("123", "999"); // does not work
MyString = MyString.Replace("123", "999"); // works
[Edit:]
If I understand your follow-up question, you could do this:
infos[1] = infos[1].Replace("1000", "1500");

Keeping only a certain line and deleting the rest in C#

I was wondering if anyone could give me a quick example of how to do this. What I want to do is parse a .txt file and delete everything but lines containing "Type: Whisper", is there any way to achieve this with relative ease?
You don't give alot of detail but something along these lines will overwrite the file with a new one with those lines removed:
var fileName = #"c:\temp\myFile.txt";
System.IO.File.WriteAllLines(
fileName,
System.IO.File.ReadAllLines(fileName)
.Where(x => !x.Contains("Type: Whisper")).ToArray());
Do Readline from 1 file and then do String.Contains over that line for "Type: Whisper" text, if you get it, jst skip. If not, just write that line to new file and delete the old file at the end.

How can I delete all the comments in my code?

I'm new to C#, and want to develope a program with which I could delete the comments after // in my code. Is there any simple code recommended for this purpose?
It has been suggested that you just search for "//" and trim.
Because you have limited yourself to single-line commands this seems like a relatively simple exercise however it has some tricky cases you need to be thinking about if you intend for the output of the program to be a valid C# application with identical behavior to the input program.
Here are some examples where just searching for "//" and trimming won't work.
Comment in Literal:
string foo = "this is // not a comment";
Comment in Comment
/* you should not trim // this one */
Comment in Comment Part Deux
// This is a comment // so don't just remove this!
Multi-line Comment Adjacency
/* you should not *//* trim this these */
There are certainly other edge cases but these are some low-hanging fruit to think about.
First point, this seems like a bad idea. Comments are useful.
Taking it as an exercise,
Edit: This is a simple solution that will fail on all the case #Bubbafat mentions (and propbably some more). It would still work OK on most source files.
read the text one line at a time.
find the last occurrence of //, if any using String.LastIndexOf()
remove the text after (including) the '//' when found
write the line to the output
ad 1: You can open an TextReader using System.IO.File.OpenText(), or File.ReadLines() if you can use Fx4
Also open an output file using System.IO.File.WriteText()
ad 3: int pos = line.LastIndexOf("//"); if (pos >= 0) { line = line.Substring(0, pos); }

Categories