Hey, I'm working on a project that writes some HTML code to a file and then opens the file up. Now, there is a lot of HTML code and I don't really want to write it all into my C# program, because I may need to change the HTML in the future. All I really need is to pass a few variables across.

Is there a way that I can search through the text file, find a specific word, ignore the equal sign and add my own variable? For example:


 var hello = "";


string hello = "Hello World";
  -Scans the document
  - Finds "var hello"
  - Ignores the =
  - Inserts hello.

Then when I open the webpage, it displays Hello?

Thanks for your help.

You can use the String.Replace method for this purpose. What I would do is replace the string [var hello = ""] with your new string. Let's say you have read the file contents into a string called contents. Here is basically how you would do it:

public string SpecifyHello(string newGreeting, string contents)
  // \" is an escape to allow " to be inserted into a string
  string search = "var hello = \"\"";
  string replacement = "var hello = \"" + newGreeting + "\"";
  contents = contents.Replace(search, replacement);
  return contents;

Hope this helps :)

#region using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Management;
using System.Resources;
using System.Media;
using System.Globalization;
using System.Windows.Forms;
using System.IO;

namespace practice
    class Program
        static void Main()

        static void html_scanner()
            string var,filename,var_mod,text;
            int count=0;
            Console.WriteLine("\nEnter the file name:\n");
            filename = Console.ReadLine();
            Console.WriteLine("\nEnter the String for Scanning:\n");
            var = Console.ReadLine();
            Console.WriteLine("\nEnter the Modified String:\n");
            var_mod = Console.ReadLine();
            Console.WriteLine("Scanning File....");

            StreamReader reader = new StreamReader(filename);
            StreamWriter writer = new StreamWriter("web2.html");

                text = reader.ReadLine();
                if (String.Compare(var,text)==0)


            while (text != null);


            StreamReader reader2 = new StreamReader("web2.html");
            StreamWriter writer2 = new StreamWriter(filename);

                text = reader2.ReadLine();



            while (text != null);

            Console.WriteLine("\nNumber of strings modified are : {0}", count);

Wrote this code, it is close to what you are trying to do, but bit of modification will make it usable for your application.

This article has been dead for over six months. Start a new discussion instead.