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");
//...
Related
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.
I recently started learning about programming with C# and I have encountered a little problem with my small task that I got.
But first let me just go through a little bit what I learned so far about strings.
So, string text = Console.ReadLine(); saves whatever the user writes into that variable.
Next, I worked with a Backpack code where the user can 1. Add items in the backpack and 2. Present the items in the backpack. Here I worked with the += operator so that whenever the user added an item it would be added to the string variable.
Now I am working with a diary/blog code. The user can:
Write a new text (with a title).
Search and present the texts written.
I am stuck because I can't just have one string variable for the text that the users writes because it will be overwritten every time the user adds a new text. And I can't use += operator since I don't want to add more text to my string variable. Every time the user adds a new text it has to be saved into a new string variable (I guess?).
I just don't know how to write this code.
A good way to fix your issue is to use Classes. Maybe you can create a Blog Class with two properties Title and Body and then all you have to do is to simply create a list of Blogs.
class Blog
{
string Title {get;set;}
string Body {get;set;}
}
Each object of Blog Class represent a new post and a list of blog will give you the list of all the blog posts.
List<Blog> blogs = new List<Blog>();
You can use a generic collection like List. They are build for gathering items of one certain type. In your case it would be: List<string> allTexts. You can add strings to it with the Add method:
List<string> allTexts = new List<string>();
string newText = Console.ReadLine();
allTexts.Add(newText);
and you can access them via the [ ] operator
string textNr4 = allTexts[3];
Note: indexing starts with 0!
If you like to search for certain parts of a text you could use LINQ
string searchWord = "and";
List<string> allMatchedTextes = allTexts.Where(text=>text.Contains(searchWord)).ToList();
this will return all strings that contain the searchWord
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.
I have a .txt file like this
Text1
Text2
Service1.wsdl
Sercice2.wsdl
NoService1.txt
NoService2.txt
Service3.txt
....
Now I want to copy the names from every existing Service (Service1.wsdl, Service2.wsdl,...) into a string inside C#, so that I can work with them later.
I need something in C# like
"get every name before ".wsdl" from the .txt file and copy them into a string so I can work with them in a loop inside C#"
I'm not going to write code for you, because I'm not able to see if you have done anything so far.
You could read the .txt with File.ReadAllLines.
Then check each element(each row is an element in this new array) if it contains the .wsdl.
And then you can copy that element and work with it.
I've solved it :)
string[] lines = File.ReadAllLines("myTXTWithAllLines").Where(s => s.Contains("wsdl")).ToArray();
File.WriteAllLines("MyTXTWithOnlyWSDLLines", lines);
I want to send multi attach in email, but have problem with those. When I put all files what want to send in one string always get error, but when put one file in one attach inside of loop thing work.
Now I have problem with copying one part of string in to another strings, don't know how to do that, do you have some solution?
Example:
txtattach.Text = "d:\\folder\\file1,d:\\folder\\file2,d:\\folder\\file3";
want to get 3 strings with context of location without "," that I can easy put it in loop.
use the split function:
string[] paths = txtattach.Text.Split(',');
One way to do this is using the Split method so you easily can iterate over the items in a loop:
foreach(var filename in txtAttach.Text.Split(','))
{
// Do something with filename
}