c# - 更改文本文件中特定行中的特定文本

标签 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);
                    }

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

最佳答案

在您的代码中,这行代码显然替换了整行 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\"";

关于c# - 更改文本文件中特定行中的特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25357116/

相关文章:

javascript - Ajax 完全没有被调用

visual-studio - 使用 VSTS 构建包含 VSTS 包和旧式 csproj 的解决方案

c# - 在 MySQL 和 C# 中获取 "both"日期和时间的正确 DateTime 格式是什么

c# - 线程问题

c# - 在使用 3 层设计模式的 Web 应用程序中,底层之一是否应该提供一些检查机制以确保……?

c# - 集成测试 .NET Code 2.2 IHostBuilder (Generic Host Builder)

c# - 如何汇总列表框列中的所有值并将其显示在文本 block 中?

c# - System.Speech.Recognition 选择识别配置文件

visual-studio - Visual Studio - 关闭解决方案资源管理器的键盘快捷方式

c# - 特性信息有什么优势?