更改文本文件中特定行的特定文本

时间:2014-08-18 05:57:17

标签: c# visual-studio c#-2.0

这是我要更改的aspx文件中的文本行

<center><body link=blue vlink=purple class=xl65 onload="processData();"><form id="mainform"
 action="http://localhost/XLEZ/DataHandler/Submit.aspx" method="post" enctype="multipart/form-
data"><input type="hidden" id="hid_extra" name="hid_extra" 
value="Machine_Inspection_20140807162226.xlsx||Machine_Inspection||Excavator 
Inspection||Excavator Inspection|Forklift Inspection|Tractor Inspection"/>

我的代码找到了这一行,我想更改此行中的表单操作,

这是我的代码,它基本上改变了整行,但我只想更改特定的文本

String Form_action ="http://\" + Request.Url.Authority+\"/XLEZ/DataHandler/Submit.aspx\"";

while ((line = sr.ReadLine()) != null)
                        {

                            if (line.Contains("form id=\"mainform\""))
                            {
                                index = count;
                            }
                            count++;
                        }
                        sr.Dispose();
                    }
                    if (index != 0)
                    {
                        var lines = File.ReadAllLines(selected_path);
                        lines[index] = Form_action ;
                        File.WriteAllLines(selected_path, lines);
                    }

但是这会用动作替换整行,我只想更改此行中的动作

2 个答案:

答案 0 :(得分:1)

在您的代码中,这行代码显然取代了整行HTML代码:

lines[index] = Form_action ;

您需要替换此行中的部分字符串。您可以执行以下操作:

String Form_action ="http://\" + Request.Url.Authority+\"/XLEZ/DataHandler/Submit.aspx\"";

while ((line = sr.ReadLine()) != null)
                        {
                        if (line.Contains("form id=\"mainform\""))
                        {
                            index = count;
                        }
                        count++;
                    }
                    sr.Dispose();
                }
                if (index != 0)
                {
                    var lines = File.ReadAllLines(selected_path);
                    int start = lines[index].IndexOf("action");
                    string newLine = lines[index].Substring(0, start + 8) + Form_action + " " + lines[index].Substring(lines[index].IndexOf("method"));
                    lines[index] = newLine;
                    File.WriteAllLines(selected_path, lines);
                }

你的&#34; Form_Action&#34;变量不会保持正确的值,因为你逃脱了&#34;在使用Request对象之前。你应该看看这个。

调整后的表格 - 行动创作:

String Form_action ="http://" + Request.Url.Authority + "/XLEZ/DataHandler/Submit.aspx\"";

答案 1 :(得分:1)

您可以使用正则表达式以更简单的方式执行此操作:

    Regex regex = new Regex(".*form id=\"mainform\".* action=\"(.+?)\" .*");

    var lines = File.ReadAllLines(selected_path);
    foreach (string line in lines)
    {
        Match match = regex.Match(line);
        if (match.Success)
        {
            string toReplace = match.Groups[1].Value;
            lines[count] = lines[count].Replace(toReplace, Form_action);
        }
        count++;
    }
    File.WriteAllLines(selected_path, lines);
相关问题