0

I am trying to replace content of data tag in each file, but getting error "System.ArgumentException: 'String cannot be of zero length. Parameter name: oldValue'" (*"Data" tag contains multiple lines of base64 encoded string)

Here is my code:

var regex = new Regex("<data>([\\s\\S]*?)<\\/data>\r\n", RegexOptions.Multiline);
var main1 = Directory.GetFiles(main1path, "demo.xml", SearchOption.AllDirectories).OrderBy(x => x).ToArray();
var main2 = Directory.GetFiles(main2path, "demo.xml", SearchOption.AllDirectories).OrderBy(x => x).ToArray();
for (var i = 0; i < Math.Min(main1.Length, main2.Length); i++)
{
    var demo1path = main1[i];
    var demo2path = main2[i];
    var demo1 = File.ReadAllText(demo1path);
    var demo2 = File.ReadAllText(demo2path);
    var data1 = regex.Match(demo1);
    var data2 = regex.Match(demo2);
    File.WriteAllText(demo1path, demo1.Replace(data1.Value, data2.Value));
}
devlin carnate
  • 8,309
  • 7
  • 48
  • 82
coffee
  • 1
  • 3
  • Which exact line does the error come from? – gunr2171 Sep 17 '19 at 17:13
  • File.WriteAllText(demo1path, demo1.Replace(data1.Value, data2.Value)); – coffee Sep 17 '19 at 17:13
  • 3
    `data1.Value` must be an empty string, meaning that your regex didn't find a match (you should see that `data1.Success` is false). – gunr2171 Sep 17 '19 at 17:17
  • 6
    Also, please don't use regex to parse XML. Use an actual XML parser. – gunr2171 Sep 17 '19 at 17:17
  • https://learn.microsoft.com/en-us/dotnet/api/system.convert.frombase64string?view=netframework-4.8 – Renan Barbosa Sep 17 '19 at 17:21
  • @gunr2171 Could you please show me how to use XML parser in place of regex. (I'm totally new to C# and trying to learn) – coffee Sep 17 '19 at 17:26
  • 2
    https://stackoverflow.com/questions/55828/how-does-one-parse-xml-files. Please Google search "How to parse xml with c#" if you need more. – gunr2171 Sep 17 '19 at 17:28
  • 2
    Related: [Why is it such a bad idea to parse XML with regex?](https://stackoverflow.com/questions/8577060/why-is-it-such-a-bad-idea-to-parse-xml-with-regex) – John Wu Sep 17 '19 at 17:38
  • Much better to do this with LINQ to XML. Can you share a [mcve] that includes the input XML and how you want to modify it? See e.g. [LINQ TO XML, How to replace values with new values c#](https://stackoverflow.com/q/11637263). – dbc Sep 17 '19 at 19:04

0 Answers0