Reputation: 750
Imagine, you are confronted with a big textfile, for example HTML, and only want to edit one line of code in this file.
The standard approach would be to first read everthing and then write everthing, including the changed text, back to a separate file, which would not be very efficient in this usecase.
I want to use a similar approach to open a file in the Editor, find the line you need and then edit this specific line.
Is there any FileIO that allows actual editing/replacing in stead of plain append or create?
EDIT: What I have in my mind so far is exactly the example that Rahul Singh gave below. But as mentioned, if I think about this approach it doesn't seem very efficient if you just want to edit one or even a few lines. In my actual problem where the question came from, the file is a HTML file in which want to insert a additional table row. But I think this use-case also is interesting to all files that contains plain text
Upvotes: 0
Views: 62
Reputation: 384
firstly please share what you have tried so far, as we dont have any idea upon data that your textFile contains, First read through out the file in streamreader and store it into string then do string.replace and do the editing, you could also use the split options and by check it by contains function do the editing. and you can always go by XSLT options but for that you need to use XPath to select
Upvotes: 0
Reputation: 2508
You can use HTML Agility Pack.
This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT.It is a .NET code library that allows you to parse "out of the web" HTML files.
For example this code fix all hrefs in HTML file:
HtmlDocument doc = new HtmlDocument();
doc.Load("file.htm");
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])
{
HtmlAttribute att = link["href"];
att.Value = FixLink(att); //FixLink() is your custom method
}
doc.Save("file.htm");
Upvotes: 1