Replacing a word in a text file - c#

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");

Related

Get only strings from binary file

I try to print to screen a string from a binary file using xaml labels, but when i display the file content I got a beautiful "corrupted" character instead of the entire file content.
I think the problem is reading the file, I already can change the label content using the most basic technique it work pretty well till today....
label.Text = mystring ;
The fact is : I have data in my binaries files that inst text (some random data that I don't care) located to the start of the file, my theory is my program start reading, read a non ascii character and stop reading...
I read using the File class, maybe the wrong thing.....
label.Text = File.ReadAllText(my_file);
So, im lock now. I don't exactly know what im supposed to do....
Hope you can help me :D
I can't tell much without looking at the text, but it seems you need to add the Encoding
Something like this:
string myText = File.ReadAllText(path, Encoding.Default);
You need to know how your binary file is structured. You need to know the encoding of the strings. A normal text file normally has markers at the beginning two or so bytes that identify its encoding if it is Unicode. This way the system can know whether its UTF-8, UTF-16, ...
If you try to read a binary file this Information is not there. Instead the reading process will most probably find unexpected binary data. So you cannot read a binary file as text. If your file is structured the way that at the beginning is binary data and later only text, just skip the first part and start reading at the start of the second part. But I don't think, that it is that easy:
if it really is binary data, chances are that the file structure is much more complicated and you need to do more work to read it.
if only the first two bytes are binary data, then maybe its a text file and you can read it without problems, you maybe only need to pass the right encoding to the reading function

Is there a magic get longest line length feature in C#

I have simple ascii text file like this:
Madonna is a celebrity
No she's not she's a serious artist
Did you see her book or the movie Truth or Dare
Argument closed
I need a method to get the length of the longest line. In this example the answer would be 47.
I can use StreamReader and open the file and read each line but it seems that there should an easier way.
Is there a simple to way solve this problem?
You can do this nicely with File.ReadLines, which has the advantage that it does not read the entire file into memory. As it returns IEnumerable<string> you can use Linq on the return value, leading to this rather nice one liner.
File.ReadLines(fileName).Max(line => line.Length)

Inserting a Line at a specific place in a txt using .net

The process I currently use to insert a string into a text file is to read the file and modify it as I write the file out again which seems to be how everyone is doing it.
Since .net has such a diverse library I was wondering if there was a specific command for inserting a string at a specific line in a txt file.
I would imagine it would look something like this:
dim file as file
file.open("filePath")
file.insert(string, location) 'this isn't actually an option, I tried
No, there's nothing specifically to do that in .NET.
You can do it very simply if you're happy to read all the lines of text in:
var lines = File.ReadAllLines("file.txt").ToList();
lines.Insert(location, text);
File.WriteAllLines("file.txt", lines);
It would be more efficient in terms of memory to write code to copy a line at a time, inserting the new line at the right point while you copy, but that would be more work. If you know your file will be small, I'd go for the above.
You could simply read all the text into a string, then use the string insert method, e.g.
File.WriteAllText("file.txt", File.ReadAllText("file.txt").Insert(startIndex, "value"));

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 to overwrite specific lines on text files

I have two text files. I'd like to copy a specific part in the first text file and replace it with a part of the second text file.
This is how I read the files:
List<string> PrevEp = File.ReadAllLines(string.Format(#"{0}naruto{1}.ass", url, PrevEpNum)).ToList();
List<string> Ep = File.ReadAllLines(string.Format(#"{0}naruto{1}.ass", url, EpNum)).ToList();
The part in PrevEp that I need: from the start until it meets a line that includes Creditw,,0000,0000,0000.
The part I would like to overwrite in Ep: from the start to a line which is exactly Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text.
I'm not so sure how may I do it. Could you lend me a hand?
Thank you very much.
Don't think of it as overwriting lines in a file, just do as you do at the moment and load it all into Lists and then you loop through Ep until you find the section you need, delete all the items from the list that you want to overwrite and the just keep track of the index and Insert the new lines into that index.
Then you write Ep to a temporary file, delete the original Ep file and rename the temporary Ep file to the original name.
It's much easier to do the manipulation in memory in nice structures than in the files, and if you have a power failure or something you won't corrupt the file with half written edits.
I would read both text files, manipulate and rewrite them instead of trying to replace and do all kinds of trickery and sorcery.
Is your problem with finding the lines, or putting together the final file?

Categories