Finding Ghosts: Programmatically Determining Ghosted/Unghosted State
First, some terminology. The terms "ghosted" and "unghosted" get thrown around a lot when talking about SharePoint site definitions, and all too often, they are used incorrectly. Here's the deal:
Ghosted: a ghosted page is one that is read directly from the site definition on the filesystem.
Unghosted: an unghosted page is one that is read from the SharePoint database and *not* a physical file
So, how can we determine if a given page is either ghosted or unghosted? Luckily, there is a single property that will tell us: "vti_hasdefaultcontent." If this property exists on a file, it is ghosted (again, on the filesystem); if the property does not exist, the file is being served from the database.
Here's the code for a simple command-line utility that will take the URL to a given page and report whether it is ghosted or unghosted:
=====
using System;
using Microsoft.SharePoint;
namespace GhostCheck
{
public class Checker
{
[STAThread]
static void Main(string[] args)
{
//if vti_hasdefaultocontent = true, it is ghosted; if unghosted, the prop doesn't exist
if(args.Length == 0 || args[0].ToString().Equals("/?"))
{
Help();
}
else
{
string sURL = args[0].ToString();
bool hasError = false;
string sGhosted = CheckGhost(sURL, out hasError);
if(hasError)
{
Console.WriteLine("\nError encountered: {0}", sGhosted);
}
else
{
Console.WriteLine("\nThe page at {0} is {1}", sURL, sGhosted);
}
}
}
static void Help()
{
Console.WriteLine("\nghostcheck <URL>");
Console.WriteLine("\nExample: ghostcheck https://<myserver>/sites/<site>/Lists/Contacts/NewForm.aspx");
}
static string CheckGhost(string FileURL, out bool ErrorFlag)
{
ErrorFlag = false;
SPSite oSite = null;
SPWeb oWeb = null;
SPFile oFile = null;
try
{
oSite = new SPSite(FileURL);
}
catch(System.Exception exSite)
{
ErrorFlag = true;
return String.Format("Error getting Site: {0}", exSite.Message);
}
try
{
oWeb = oSite.OpenWeb();
}
catch(System.Exception exWeb)
{
ErrorFlag = true;
return String.Format("Error getting Web: {0}", exWeb.Message);
}
try
{
oFile = oWeb.GetFile(FileURL);
}
catch(System.Exception exFile)
{
ErrorFlag = true;
return String.Format("Error getting File: {0}", exFile.Message);
}
System.Collections.Hashtable oHash = oFile.Properties;
if(oHash.ContainsKey("vti_hasdefaultcontent"))
{
return "ghosted (on file system)";
}
else
{
return "unghosted (in database)";
}
}
}
}
=====
This utility uses the SharePoint object model, and so MUST BE RUN ON THE SERVER, not from a client.
Usage:
ghostcheck.exe <URL>
Example:
ghostcheck.exe https://myserver/sites/mysite/Lists/Contacts/NewForm.aspx