-5

I have on text s this lines:

myData = myData.Replace(".jpg", ">JPG<");
myData = myData.Replace(".gif", ">GIF<");
myData = myData.Replace(".png", ">PNG<");
myData = myData.Replace(".tif", ">TIF<");

and on my C# program i wont one by one, on a cicle for:

for (int l=0; w<listWithLines.Count;l++)
{
// MY LINE
// listWithLines[l]
}
r-magalhaes
  • 427
  • 2
  • 9
  • 18

4 Answers4

0

I dont think you can do that, you can compile a block of code from an external source using CodeProviders etc but I dont think you can just drop it into a predefined scope like you seem to want to (the scope being within your for loop), unless you can load it as a block and pass it in to a method (which would do the loop) as an Action.

Grofit
  • 17,693
  • 24
  • 96
  • 176
0

I'm not aware of an easy way to compile and run lines of code from a text file this way. But if you were to provide methods for myData objects to be serialized and deserialzed using XML you could read in lines from an external file to do something similar to this.

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
0

If your intention is just to do string replacement (as in the example lines), and you are able to modify the text list, the best approach would be to provide just the replacement tokens in the list:

.jpg,>JPG<
.gif,>GIF<
.png,>PNG<
.tif,>TIF<

Then your C# code can be modified like this:

for (int l=0; w<listWithLines.Count;l++)
{
    string[] strTokens = listWithLines[l].Split(',');
    // MY LINE
    myData = myData.Replace(strTokens[0], strTokens[1]);
}
0

You could maybe do that but it's lot of work with things like Reflection.Emit. Pretty sure you'd have to an entire class as well You could use IronPython or one of the other DLR implementations to do it, but would be a good bit of work as well Turn it into an xml

<Replaces>
<Replace from=".jpg" to=">JPG<" />
<Replace from=".gif" to=">GIF<" />
</Replaces>

Then do something like

XmlDocument doc = new XmlDocument();
doc.Load("Replaces.xml")
foreach(XmlNode replaceNode in doc.DocumentElement.SelectNodes("Replaces/Replace"))
{
  myData = myData.Replace(replaceNode.Attributes["from"].Value, replaceNode.Attributes["to"].Value);
}
Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39