我有一个文件,我正在打开和阅读。在这个文件中,我有几个关键词,我用不同的DB东西替换。
我的问题:我需要能够从读取文件中删除特定文本。不仅仅是一个字。我没有尝试过任何工作。完成后,.Remove方法返回并清空文件。这是我的读者代码
using (StreamReader reader = File.OpenText(@"\\GTU-FS02\ScanTests\RLA.htm"))
{
/* Commented out. TRIED, but does not work
string fill = reader.ReadToEnd();
string toRemove = "GTU Renewal Application (a shorter, simplified renewal form)";
int i = fill.IndexOf(toRemove);
if (i > 1)
{
fill.Remove(i, toRemove.Length);
}
*/
string toRemove = "GTU Renewal Application (a shorter, simplified renewal form)";
string fill = reader.ReadToEnd();
string fill2 = null;
if (fill.Contains(toRemove))
{
fill2 = reader.ReadToEnd().Replace("UWNAME", UW).Replace("ClientFName", subFname).Replace("ExDate", ExpDate).Replace("UwEmail", UwEmail(UW))
.Replace("CinSured", client).Replace("&", amperSand).Replace(toRemove, "");
}
line = fill2;
}
你所看到的是解决这个问题的不同尝试。我可以轻松找到我正在寻找的内容,但我无法删除或替换文本。文本总是一样的,所以我知道我可以这样找。有谁知道如何做到这一点?
第一种方法(注释的方法)不适用于字符串是不可变对象的简单原因。 Remove方法返回一个新字符串,不会更改调用该方法的字符串。因此,您的代码应该简单地修复
line = fill.Remove(i, toRemove.Length);
第二种方法不起作用,因为你已经调用了ReadToEnd两次。所以第二次流已经到文件的末尾并且无法读取fill2变量中的任何内容。只需删除第一个ReadToEnd,然后获取Replace调用的结果。 (同样字符串是不可变的,所有字符串方法都执行它们的任务并返回一个新字符串而不更改调用字符串)
string toRemove = "GTU Renewal Application (a shorter, simplified renewal form)";
string fill = reader.ReadToEnd();
if (fill.Contains(toRemove))
{
line = fill.Replace("UWNAME", UW)
.Replace("ClientFName", subFname)
.Replace("ExDate", ExpDate)
.Replace("UwEmail", UwEmail(UW))
.Replace("CinSured", client)
.Replace("&", amperSand)
.Replace(toRemove, "");
}
我试过了,它的确有效。 https://dotnetfiddle.net/lxtVGN
检查reader.ReadToEnd();
返回的是什么,
不要使用null初始化字符串,始终使用""
或String.Empty
初始化它