简体   繁体   中英

c# Read lines from a file and replace with text from DataGridView Data

I am relatively new to c#, I am creating an windows application which would read all the lines from a text file. The user will input the string which needs to be replaced in Column[0] and the text with which it needs to be replaced in Column 1 of the DataGridView control.

I have created two string arrays column0 and column1. However, I am getting an error while replacing the string in line (column0, column1)

The following is my code:

        string[] column0 = new string[dgvMapping.Rows.Count];
        string[] column1 = new string[dgvMapping.Rows.Count];
        int j = 0;
        foreach(DataGridViewRow row in dgvMapping.Rows)
        {
            if (!string.IsNullOrEmpty(Convert.ToString(row.Cells[0].Value)))
            {
                column0[j] = Convert.ToString(row.Cells[0].Value);
                column1[j] = Convert.ToString(row.Cells[1].Value);
                j++;
            }
        }

        var _data = string.Empty;

        String[] arrayofLine = File.ReadAllLines(ofd.FileName);

        using (StreamWriter sw = new StreamWriter(ofd.FileName + ".output"))
        {
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                string line = arrayofLine[i];
                line = line.Replace(column0[i], column1[i]);
                sw.WriteLine(line);
            }
        }

I am using OpenFileDialog to select the file.

The Error While Executing: 在此处输入图片说明

Stuartd is correct… there are more lines in the file than there are elements to search. I am not sure what the search is doing in a sense that it seems somewhat limited. The code appears to search for each item depending on what line it is. The searched value in column 0 and the replace value in column 1 of row 0… will only replace those values for the FIRST line in the file. The DataGridView s second row values will search/replace only the SECOND line and so on. This seems odd.

Example the two string arrays (column0 and column1) have sizes set to the number of rows in dgvMapping . Let's say there are 5 rows in the grid, then the array sizes will be 5 strings. When you start the loop to write the strings, the loop starts at 0 and stops at the number of lines in the file. The code uses this i variable as an index into the two arrays. If there are more lines in the file, than there are rows in the grid… then you will get the error.

Again, this seems odd to do the search and replace this way. Assuming you want to search for EACH term in all the rows in column 0 and replace the found searched string with the replace string in column 1, then you will need to loop through EACH row of the grid for EACH line in the file. This will replace ALL the search/replace terms in the grid with ALL the lines in the file. If this is what you what to accomplish below is one way to achieve this, however…there are possibly better ways to accomplish this.

The code below reads the file into one big string. Then the code loops through ALL the grid rows to search/replace the strings in the big string. Hope this helps.

 string bigString = File.ReadAllText(ofd.FileName);
  try {
    using (StreamWriter sw = new StreamWriter(ofd.FileName + ".output")) {
      for (int k = 0; k < dgvMapping.Rows.Count; k++) {
        if (dgvMapping.Rows[k].Cells[0].Value != null && dgvMapping.Rows[k].Cells[1].Value != null) {
          string searchTerm = dgvMapping.Rows[k].Cells[0].Value.ToString();
          string replaceTerm = dgvMapping.Rows[k].Cells[1].Value.ToString();
          if (searchTerm != "") {
            bigString = bigString.Replace(searchTerm, replaceTerm);
          } else {
            // one of the terms is empty
          }
        } else {
          // one of the terms is null}
        }
      }
      sw.WriteLine(bigString);
    }
  }
  catch (Exception ex) {
    MessageBox.Show("Write Erro: " + ex.Message);
  }

You are looping around a file of unknown number of lines, and assuming that the count of lines in the grid is exactly the same as that of the file. Your code will only work if both the file and the gridView have the same number of lines.

One of the solutions, is to loop over the array of lines (as you have already did), and search for the GridViewRow in which the current line contains a key in your DGV. If this is the case, then replace all the occurences of the key by the value (obtained from the gridView) in that line, otherwise do nothing.

Check out the code below :

// Convert the row collection to a list, so that we could query it easily with Linq
List<DataGridViewRow> mySearchList = dataGridView1.Rows.Cast<DataGridViewRow>().ToList();
const int KEY_INDEX = 0; // Search index in the grid
const int VALUE_INDEX = 1; // Value (replace) index in the grid
for (int i = 0; i < arrayofLines.Length; i++)
{

    string line = arrayofLines[i];

    // Get data grid view Row where this line contains the key string
    DataGridViewRow matchedRow = mySearchList.FirstOrDefault(obj => line.Contains(obj.Cells[KEY_INDEX].Value.ToString()));
    // If this row exists, replace the key with the value (obtained from the grid)
    if (matchedRow != null)
    {
        string key = matchedRow.Cells[KEY_INDEX].Value.ToString();
        string value = matchedRow.Cells[VALUE_INDEX].Value.ToString();

        line = line.Replace(key, value);

        sw.WriteLine(line);
    }
    else
    {
        // Otherwise, do nothing
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM