Joseph Michael Pesch
VP Programming

Perform Content Replace on Each File in Folder

by 27. June 2010 23:46

using System.IO;

 

namespace FileIO

{

  class Program

  {

    static void Main(string[] args)

    {

      string[] fileEntries = Directory.GetFiles(@"C:\JMPBlog\App_Data\posts");

      foreach (string fileName in fileEntries)

      {

        string fileContents = File.ReadAllText(fileName)

          .Replace("href=\"~/file.axd", "href=\"JMP/Blog/file.axd")

          .Replace("src=\"~/image.axd", "src=\"JMP/Blog/image.axd");

        if(fileContents.Contains("image.axd"))

          System.Diagnostics.Debug.WriteLine("found");

        File.WriteAllText(fileName, fileContents);

      }

 

    }

  }

}

 

Using BlogEngine.net made the below modifications to allow it to run in sub-directory of root website.

 

 

Admin/Pages/Pages.aspx.cs

 

private void btnUploadImage_Click(object sender, EventArgs e)

{

  string relativeFolder = DateTime.Now.Year.ToString() + Path.DirectorySeparatorChar + DateTime.Now.Month.ToString() + Path.DirectorySeparatorChar;

  string folder = BlogSettings.Instance.StorageLocation + "files" + Path.DirectorySeparatorChar;

  string fileName = txtUploadImage.FileName;

  Upload(folder + relativeFolder, txtUploadImage, fileName);

  // JMP: Added ~ to front of url to make it relative to the root of the application

  string path = Utils.RelativeWebRoot.ToString();

  string img = string.Format("<img src=\"~/{0}image.axd?picture={1}\" alt=\"\" />", path, Server.UrlEncode(relativeFolder.Replace("\\", "/") + fileName));

  txtContent.Text += img;

}

 

private void btnUploadFile_Click(object sender, EventArgs e)

{

  string relativeFolder = DateTime.Now.Year.ToString() + Path.DirectorySeparatorChar + DateTime.Now.Month.ToString() + Path.DirectorySeparatorChar;

  string folder = BlogSettings.Instance.StorageLocation + "files" + Path.DirectorySeparatorChar;

  string fileName = txtUploadFile.FileName;

  Upload(folder + relativeFolder, txtUploadFile, fileName);

  // JMP: Added ~ to front of url to make it relative to the root of the application

  string a = "<p><a href=\"~/{0}file.axd?file={1}\">{2}</a></p>";

  string text = txtUploadFile.FileName + " (" + SizeFormat(txtUploadFile.FileBytes.Length, "N") + ")";

  txtContent.Text += string.Format(a, Utils.RelativeWebRoot, Server.UrlEncode(relativeFolder.Replace("\\", "/") + fileName), text);

}

 

 

Tags:

BlogEngine.NET | C#

Comments are closed