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?
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");
FileName="1.pdf",filepath="f:/test1"
FileName="2.pdf",filepath="f:/test2"
FileName="3.pdf",filepath="f:/test3"
FileName="4.pdf",filepath="f:/test4"
FileName="5.pdf",filepath="f:/test5"
FileName="6.pdf",filepath="f:/test6"
I don't want to create a new file. Overwriting in a same file is ok
I tried the following.
var reader = File.OpenText("f:/test5");
reader. // ?
I don't know what to put after reader. If any alternate way is there, provide me a solution.I want to remove only a particular line based on the unique file name. If I am having 5.pdf as the filename, then I need to delete or remove the entire line which is "FileName="5.pdf"...line from the file. I don't want to overwrite the contents in a new file again. Provide me a solution. Thanks.
You cannot reomve a line from a textfile without rewriting the file. Do something like this
string filename =
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
"Test1.txt");
string[] lines = File.ReadAllLines(filename);
var list = new List<string>(lines);
list.RemoveAt(4);
File.WriteAllLines(filename, list.ToArray());
EDIT:
You can find a line with a specific filename like this:
int index = list.FindIndex(s => s.EndsWith("/test5\""));
// Or whatever test is appropriate.
if (index >= 0) {
list.RemoveAt(index);
File.WriteAllLines(filename, list.ToArray());
}
If you don't mind using gnu tools, you can use sed http://en.kioskea.net/faq/1451-sed-delete-one-or-more-lines-from-a-file
It's technically impossible, as much as I'm aware of, as OS will create a new IO artifact.(By the way not very sure on this) .
But what is much more important, that it's extremely dangerous. IO operations are subjects to fail, so you have to gurantee in some way consistency of your operations on file.
One of possible ways of doing this is:
write all lines, except those ones you want to skip, into the new TEMP file
rename your old file with some other temp name
rename fisrt TEMP file in name of previous file
delete original file.
No matter what utility you use or what code you write, the operating system will always create a new file to do it.
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"));
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.