I have a text file...
HELLO
GOODBYE
FAREWELL
.. and two string variables, requested and newname.
I am trying to write a program, that removes 'requested' from the text file and adds 'newname'. However I do not know the concepts and the code to do so. The only concept I can think of is adding all lines to an array then removing 'requested' from the array and adding 'newname' ... but I don't know the code.
I apologies if this is a stupid question, I am new to c#. Help is much appreciated. :)
Your idea should work fine.
Here's a link on how to get the text file contents into a list collection.
http://www.dotnetperls.com/readline
Then you can use List.Add("newname"); and List.Remove("requested");
No stupid questions btw, only stupid ppl to post complaints about it :D
As simple as:
string path = "file path here";
List<string> lines = File.ReadAllLines(path).ToList();
lines.RemoveAll(line => line.Equals(requested));
lines.Add(newname);
File.WriteAllLines(path, lines);
Related
This question already has answers here:
Extract comments from .cs file
(2 answers)
Closed 1 year ago.
Im trying for a while to split code file (treated as text file) by the comments that in it.
For example, for the input:
// Hi guys, I am trying to get some help here.
// I really tried to do this alone.
/* But i still search for help
in our bes friend Google.*/
I expect to get the output:
Hi guys, I am trying to get some help here.
I really tried to do this alone.
But i still search for help in our bes friend Google.
so basiclly i want to recognize that there is a comments in the file (by the symbols // and /* */) and enter the comments in a list (each comment in a differend cell).
I am trying to do so by the code line: codeFile.Split('//', '/', '/');
But with no success.
As well, since it is possible for multi-line comment when using the "/* */" symbol, how can i enter the intire string between them to my list since I am run over the file by the lines?
Thanks in advence.
I would do something like :
Read your file line per line
Check if line match with Regex for your different criterias.
Build a new string (with line break if needed) using the information you got from your checking. You will be able to handle the multi line factor.
Hope this could be helpful.
I'm using File.ReadLines().ToList() to read a regular text file into a List<string>.
The text file has 2 blank lines, like so ('View all characters' enabled in notepad++ for clarity):
Example code:
List<string> lines = null;
try{
lines = File.ReadLines("C:\path\to\file.txt").ToList();
}catch(Exception e){
//code here to handle e
}
Console.WriteLine(lines.Count.ToString());
Prints "1" to console.
My question is, why does my list that is generated by File.ReadLines().ToList() only have a Count of 1 when the file has 2 lines? Is a blank line at the end of the file just discarded by default? (it seems so)
Thanks to Hans Passant for the answer. I was hoping he'd post it here, but I'm going to go ahead and do it now, as it looks like this question is very close to being closed (not sure why???) and I think this could help others in the future.
Answer: Notepad++ is showing a 2nd line that doesn't actually exist in the file. By opening the file with vim in WSL, I was able to see that there is one (1) line in the file, and no more than that.
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'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");
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.