0

I am trying to replace all the urls from a file with others

To this end I do something like this:

 private static void findAndReplaceImgURLs(string s) { var server = HttpContext.Current.Server; var cssLines = File.ReadLines(server.MapPath(s)); int indexer = 0; foreach (string line in cssLines) { int startPosition = line.IndexOf("url(\""); int endPosition = line.IndexOf(".png)"); if (startPosition != -1 && endPosition != -1) { //replace urls } indexer++; } } 

I DON’T want to just replace all the strings from a certain index, I want to replace from one index to another all the chars in between. How can I do this?

2
  • 2
    You should probably use Regex.Replace for this. Commented Nov 29, 2013 at 20:56
  • 1
    Also, note that you generally won't be allowed to modify the variable declared for a foreach loop. What should happen to the modified line; where should it go? Commented Nov 29, 2013 at 20:58

4 Answers 4

1

You may want to declare prefix/postfix

string prefix = "url(\""; string postfix = ".png)"; 

and then

// replace urls newLine = line.Substring(0, startPosition) + prefix + newUrl + postfix + line.Substring(endPosition + posfix.Length); // todo: put newLine in result, e.g. List<string> 

So you will end up with something like:

var result = new List<string>(); foreach (string line in cssLines) { string prefix = "url(\""; string postfix = ".png)"; int startPosition = line.IndexOf(prefix); int endPosition = line.IndexOf(postfix); if (startPosition != -1 && endPosition != -1) { //replace urls string newLine = line.Substring(0, startPosition) + prefix + newUrl + postfix + line.Substring(endPosition + posfix.Length); result.Add(newLine) } } 
Sign up to request clarification or add additional context in comments.

Comments

1

Conisder using Regex.Replace as follows...

string output = Regex.Replace(input, "(?<=url(\).*?(?=.png)", replaceText); 

Good Luck!

Comments

0

One option is to read the CSS contents from the file and call Replace:

var cssContent = File.ReadAllText("styles.css"); cssContent = cssContent.Replace("url('../images/", "url('../content/"); File.WriteAllText("styles.css", cssContent); 

Comments

0

Using string format.

 string newLine = String.Format ("{0}{1}{2}{3}{4}",line.Substring(0, startPosition),prefix, newUrl,postfix,line.Substring(endPosition + posfix.Length)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.