更改文本文件中特定行中的特定文本
本文关键字:文本 文件 | 更新日期: 2023-09-27 18:18:38
这是我想更改的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);
}
但是这用动作代替了整行,我只是想改变这一行的动作
在你的代码中,这行代码显然取代了整行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);
}
你的"Form_Action"变量不会保存正确的值,因为你在使用Request对象之前转义了"。你应该看看这个
调整后的表单-动作创建:
String Form_action ="http://" + Request.Url.Authority + "/XLEZ/DataHandler/Submit.aspx'"";
你可以用更简单的方式使用正则表达式:
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);