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"));
Related
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'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");
So this is just a thought... Say I wanted to insert a line into a file at the first linebreak, but I didn't want to read the entire file into memory. Is there a way to just read the file into memory line by line and then, when the first linebreak is reached, insert a line and close the file reader?
Thank you!
Sorry for the earlier typo in my title/description
you can read one byte at a time and intercept the line break character. Then at that position do a stream.WriteLine(). You'll hve to open file for read+write
Edit: I thought of using the FileStream object, but I'm not sure. Any for now try the suggestion mentioned here: http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/e5077949-5d23-4d26-a530-6d503745a197
Edit again: check How to both read and write a file in C#
Try the following:
using (StreamWriter w = File.AppendText("test.txt"))
{
w.Write("\r\nTest");
w.Flush();
w.Close();
}
Update:
For inserting the line in existing text file (I assume you're working with text files since you mentioned line break): there isn't a way to do it with file I/O API - you must read the text after the first line break, overwrite the file and add original trailing text.
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.
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?