1

I have a folder named "DocSamples" on the file system, this folder has 100 HTML files and one cascading style sheet file named "docStyle.css", i want to add a reference to this style sheet <link rel="stylesheet" href="docStyle.css">to each HTML file in the folder using Console Application (C#).

Any idea on how I can implement this?

Thank you,

1
  • Hello Mohammad, I suggest using a filereader and loop over each file. Then, for each file you do a string filetext = File.ReadAllText(fileName);. And then do a filetext.replace("</head>", "<link rel="stylesheet" href="docStyle.css"></head>"). And of course save the file afterwards :) Commented Mar 10, 2016 at 11:11

2 Answers 2

1

I would suggest something like:

// Get all files
string filepath = Environment.GetFolderPath("Filepath here");
DirectoryInfo d = new DirectoryInfo(filepath);

//Handle each file
foreach (var file in d.GetFiles("*.html"))

    // Get all text from 1 file
    string readText = File.ReadAllText(file.FullName);
    // Add css
    readText = readText.Replace("</head>", @"<link rel="stylesheet" href="docStyle.css"></head>")

    // Save file with modifications
    File.WriteAllText(file.FullName, readText);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Thank you Dieter for your response, much appreciated, i edited your code and used the below code, and it's working fine

    static void Main(string[] args)
        {
            string[] htmlFiles = Directory.GetFiles("systemDrive\\Doc samples", "*.html");


//Handle each file
foreach (var htmlFile in htmlFiles)
{
    // Get all text from 1 file
    string readText = File.ReadAllText(htmlFile);
    // Add css
    readText = readText.Replace("</head>", @"<link rel='stylesheet' href='docStyle.css'></head>");

    // Save file with modifications
    File.WriteAllText(htmlFile, readText);
}
        }

Thanks again.

1 Comment

You're welcome. Just be aware that you can't run it twice on the same file, else you'll be referencing the css twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.