C# 更改文本文件中特定行中的单独文本
这是我要更改的aspx文件中的文本行C# 更改文本文件中特定行中的单独文本,c#,visual-studio,c#-2.0,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="hidd
<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"/>
但是这用action替换了整行代码,我只想更改这行代码中的action在您的代码中,这行代码显然替换了整行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”变量将不包含正确的值,因为您在使用请求对象之前转义了“Form_Action”
调整表单操作创建:
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);
为什么不使用?@Hassansar使用visual studio 2008和DOT NET Framework 2.0是的,.NET 2.0也提供DLL。我如何才能在这行中找到“/XLEZ”索引,就像您在回答中使用“action”和“method”一样我只想++“在htp//:之后和/XLEZ之前获取当前IP地址…您可以像其他字符串一样使用'lines[index].IndexOf(“XLEZ”)'找到它,或者您只需调整表单动作字符串的创建。我将用调整后的版本更新我的答案。
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);