Programmatically adding files to EPiServer’s File System
Posted on November 23, 2010 by Frederik Vig in C#, Code Snippet, EPiServerHere’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.
- Created a scheduled job
- Used FindPagesWithCriteria to find all pages
- Copied the replacement files locally to the sites server
- 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.
Marthin Freij says:
Post Author November 23, 2010 at 13:40Good stuff. However, be careful with catching generic exceptions.
Johan Pettersson says:
Post Author November 23, 2010 at 15:28It’s also good practice to check out the file
IVersioningFile versioningFile;
if (file.TryAsVersioningFile(out versioningFile))
{
if (!versioningFile.IsCheckedOut)
{
versioningFile.CheckOut();
}
using (Stream stream = file.Open(FileMode.Create, FileAccess.Write))
{
StreamConsumer.CopyToEnd(postedFile.InputStream, stream);
}
versioningFile.CheckIn(comment ?? string.Empty);
}
Frederik Vig says:
Post Author November 23, 2010 at 15:43@Marthin – good catch! Updated the code now.
@Johan – it only takes a couple of milliseconds to update each image, so no point in adding the check-in/check-out overhead imho.