Reputation: 4962
I have a text file in which I add, update and delete data (Contacts). Each contact is in one line. Now when i delete a contact through my application, I am deleting a line in my file (Replacing the contact with a empty string) This is resulting a empty line in between contacts. I don't want this empty line. This is the piece of code that I wrote:
private void btn_condel_Click(object sender, EventArgs e)
{
bufferedListView1.Items.Clear();
string fileContents = File.ReadAllText("C:\\sample.txt");
string replacedContents = fileContents.Replace(txt_editname.Text + "@" + txt_editno.Text,"");
File.WriteAllText("C:\\sample.txt", replacedContents);
// Rest of the code
What do I need to do to eliminate this empty line while replacing the data in the file.
Upvotes: 0
Views: 2683
Reputation: 2168
I haven't tried it, but this should work: Read the file into a string array, convert it to a list (because you can't remove an item from an array), remove the contact and write the rest back to a file. That works even better if you parse the text file (btw: cant you use a XML file...?) into your own contact data type. Then you have a List and can delete an object from there.
string[] lines = File.ReadAllLines("C:\\sample.txt");
List<string> list = lines.ToList<string>();
list.Remove(txt_editname.Text + "@" + txt_editno.Text);
File.WriteAllLines("C:\\sample.txt", list.ToArray());
Upvotes: 0
Reputation: 3798
Try this,
string fileContents = File.ReadAllText("C:\\sample.txt");
string replacedContents = fileContents.Replace(txt_editname.Text + "@" + txt_editno.Text,"");
File.WriteAllText("C:\\sample.txt", replacedContents.Trim());
Upvotes: 0
Reputation: 4965
It looks like the easiest way to fix this would just be to grab the new line:
string replacedContents = fileContents.Replace(
txt_editname.Text + "@" + txt_editno.Text + System.Environment.NewLine,"");
Upvotes: 2