user3706539
user3706539

Reputation: 27

Deleting current string array from a file C# asp.net

Just a simple newbie question. I want to delete the displayed string in an "accepted" button. Once the "accepted" button is clicked the displayed array is written in another file, however I need the displayed one line array to be deleted from this file. Thanks for your time. Much appreciated!!!

Below is my code:

    StreamReader srAc = new StreamReader(Server.MapPath("~") + "\\App_Data\\UserEntryNew.txt");

    string allAccept = srAc.ReadToEnd();

    string[] allAcceptArray = allAccept.Split('\n');

    string accepted = "";

    for (int i = 0; i < allAcceptArray.Length; i++)
    {
        if (allAcceptArray[i] == modTextBox.Text)
        {
                accepted = allAcceptArray[i];
        }
    }

Upvotes: 0

Views: 267

Answers (2)

Kami
Kami

Reputation: 19447

If you are not comfortable with Linq, an Array approach might work something like this.

// Read the data
string[] allAcceptArray = rdr.ReadToEnd().Split('\n');

//identify item index - \r might be required
int idx = Array.IndexOf(allAcceptArray, modTextBox.Text);

// Create output string without item
string rtn = string.Join("\n", allAcceptArray, 0, idx);
rtn += string.Join("\n", allAcceptArray, idx+1, allAcceptArray.Length - idx-1);

// Write to file
using (StreamWriter swOut =
    new StreamWriter(Server.MapPath("~") + "\\App_Data\\UserEntryNew-1.txt")))
{
    swOut.Write(rtn);
}

It works similar to your current code, but rather then identify the item via a for loop, we use the Array.IndexOf() function. Then recombine the array excluding the item, and write to disk.

Upvotes: 1

Philip Pittle
Philip Pittle

Reputation: 12325

You can use linq to remove the entry from the array. Assuming you have an array allAcceptArray and you want to remove modTextBox.Text from the array:

 allAcceptArray = allAcceptArray.Where(x => x != modTextBox.Text).ToArray();

Upvotes: 1

Related Questions