Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear All,

Now i have one problem. Here i have one text file. And i wanna write particular line of that file based on my need. While the above writing process all other lines are didnt change. I did the above opereation again and again still my need is completed. Here i dont need REPLACE Technique. All Replies are Welcome.



Thanks in Advance

Dhinesh Kumar.V
Posted
Updated 7-Aug-12 1:48am
v2

There is a major problem here: text files do not have a replace-line, or indeed any concept of "lines". All they are is a collection of characters which make up the whole file. Some of those characters mark a line end, but there is nothing special about them - if you replace a single character that happens to be a newline character, the line before and the line after will be concatenated together.

If you want to replace the text of a line in the text file, you have to read the whole file, replace the text, and the write the whole file again, or:

1) Open a new file
2) Read and copy up to the point of the change
3) Read the data to be changed and write the changed data instead
4) Read and copy up to the end of file.
5) Close both files.
6) Delete the original, and rename the new file.
 
Share this answer
 
Comments
fjdiewornncalwe 9-Aug-12 11:07am    
+5. Excellent approach.
There is an easy way if you want process not very large text file:

C#
RichTextBox textBox = new RichTextBox()
{
    Text = File.ReadAllText(fileName),
    WordWrap = false
};

string firstLine, secondLine;

firstLine = textBox.Lines[0];
secondLine = textBox.Lines[1];

textBox.Lines[0] = secondLine;
tectBox.Lines[1] = firstLine;


After all write the textBox.Text on your file.

Is that what you asked?
 
Share this answer
 
v5
Comments
Dhinesh kumar.V 9-Aug-12 6:42am    
can you explain your code brief. Because i have little bit confusion.
[no name] 9-Aug-12 11:06am    
If I understand truly you want to replace two line of your file which is text.
Maybe it is not a professional suggestion but it works.
this sample replaces first line and second line instead of each other.
Where do you miss?
fjdiewornncalwe 9-Aug-12 11:09am    
This could work, but you're going to run into serious issues if the file is quite large.
This approach is also extremely inefficient because of the overhead required to do what you are doing here. I'm not voting on your answer, but felt that a note indicating the pitfalls of this approach be made. Cheers.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900