I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.
Any suggestions or examples would be greatly appreciated?
Related Questions
I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.
Any suggestions or examples would be greatly appreciated?
Related Questions
The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.
There is no generic delete-a-line-from-file function, as far as I know.
Read and remember each line
Identify the one you want to get rid of
Forget that one
Write the rest back over the top of the file
One way to do it if the file is not very big is to load all the lines into an array:
string[] lines = File.ReadAllLines("filename.txt");
string[] newLines = RemoveUnnecessaryLine(lines);
File.WriteAllLines("filename.txt", newLines);
If the line you want to delete is based on the content of the line:
string line = null;
string line_to_delete = "the line i want to delete";
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
if (String.Compare(line, line_to_delete) == 0)
continue;
writer.WriteLine(line);
}
}
}
Or if it is based on line number:
string line = null;
int line_number = 0;
int line_to_delete = 12;
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
line_number++;
if (line_number == line_to_delete)
continue;
writer.WriteLine(line);
}
}
}
Hi..
I believe this link will be useful: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/d0a2eddf-d06e-4d0a-93ce-166e4f116c32
You can actually use C# generics for this to make it real easy:
var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
file.RemoveAt(12);
File.WriteAllLines("C:\\path", file.ToArray());
Are you on a Unix operating system?
You can do this with the "sed" stream editor. Read the man page for "sed"
What? Use file open, seek position then stream erase line using null.
Gotch it? Simple,stream,no array that eat memory,fast.
This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en
Fileopen(1,"text.ini") dim line as string dim currentpos as long while true line = lineinput(1) dim namevalue() as string=split(line,"=") if namevalue(0)="line name value that i want to edit" then currentpos=seek(1) fileclose() dim fs as filestream("test.ini",filemode.open) dim sw as streamwriter(fs) fs.seek(currentpos,seekorigin.begin) sw.write(null) sw.write(namevalue+"="+newvalue) sw.close() fs.close exit while end if msgbox("org ternate jua bisa, no line found") end while
that's all..use #d