CSC510207. Using SPWeb.GetFile method is preferable.

Description

Use the SPWeb.GetFile method instead of SPFolder.Files["WordTemplate.docx"]. Because SPFolder.Files will fail with an ArgumentException if the file does not exist. Besides, performance issues with SPFolder.Files - it loads all files in the target folder.
SPWeb.GetFile method always returns an object. If the file does not exist, the method returns an SPFile object whose Exists property is set to false.
There are still circumstances in which GetFile could return null. Hence, a helper method is desirable if you have many such file operations.

static SPFile GetExistingFile(SPWeb web, string serverRelativeUrl)
{
   SPFile file = null;
   bool exists = false;
   try
   {
      file = web.GetFile(serverRelativeUrl);
      if (file != null)
      {
         exists = file.Exists;
      }
   }
   catch (ArgumentException)
   {
      exists = false;
   }
   if (!exists)
   {
      return null;
   }
   return file;
}

Links

SPFolder class
SPWeb.GetFile method

Last edited May 28, 2014 at 3:14 PM by dvd73, version 6

Comments

No comments yet.