Programmatically adding files to EPiServer’s File System

Posted on November 23, 2010 by Frederik Vig in C#, Code Snippet, EPiServer

Here’s a quick code snippet that I used for replacing files on an EPiServer site. A little background, I got asked by a customer to upload a new version of a bunch of images they had in the PageFiles directory of 500 different pages in EPiServer.

In short here are the steps I took.

  1. Created a scheduled job
  2. Used FindPagesWithCriteria to find all pages
  3. Copied the replacement files locally to the sites server
  4. Called the AddFileToEPiServer method (see code below)

The method looked something like this.

public static void AddFileToEPiServer(string fileName, string filePath, PageData pageData)
{
	// Make sure the file exists
	if (!File.Exists(filePath))
	{
		return;
	}
 
	// Get the PageFiles directory of the page
	UnifiedDirectory destDir = pageData.GetPageDirectory(true);
 
	try
	{
		// bypass access check
		destDir.BypassAccessCheck = true;
 
		// If the file exists, use it
		UnifiedFile file = HostingEnvironment.VirtualPathProvider.GetFile(VirtualPathUtilityEx.Combine(destDir.VirtualPath, VirtualPathUtility.AppendTrailingSlash(fileName))) as UnifiedFile;
 
		if (file == null)
		{
                        // if not create it
			file = destDir.CreateFile(fileName);
		}
 
		// open the replacement file and read its content
		byte[] fileContent;
		using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
		{
			fileContent = new byte[fileStream.Length];
			fileStream.Read(fileContent, 0, fileContent.Length);
		}
 
		// write the content to the file (that exists in EPiServer's file system)
		using (Stream stream = file.Open(FileMode.Create, FileAccess.Write))
		{
			stream.Write(fileContent, 0, fileContent.Length);
		}
	}
	catch (IOException ex)
	{
		// logging
	}
}

For more information on FileStream and Stream see MSDN: FileStream Class and Stream Class.

Hope this helps.

Related Posts: