Referencing SharePoint SPFiles

The SharePoint SPFile represents a file in the SharePoint website. This file can be several type of elements in the SharePoint: webparts page, an item in the SharePoint document library or a file in the SharePoint folder.

The SharePoint SPFiles inherit SystemObject and can be referenced as Microsoft.SharePoint.SPFile.

You can use two methods to return file object: GetFile and GetFileAsString. Both these methods are part of SPWeb class. Alternatively, you can use Files property of both SPWeb and SPFolder classes. The use of Files property will return SPFileCollection object with the collection of files for wither site or folder.

Example below provides with the good introduction into usage of SPFile object. First, we get file from the folder and then uploading it into document library.

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
 
class CreateSite
{
    static void Main(string[] args)
    {
        if ((args.Length == 0))
        {
            args = new string[7];
            args = GetParams(ref args);
        }
        AddSPSiteCollection(args);
    }
 
    private static bool AddSPSiteCollection(string[] args)
    {
        try
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = site.AllWebs["SiteName"];
            SPWebCollection col = site.AllWebs["SourceWeb"].Webs;
 
            SPFile file = web.GetFile("folderName/fileName");
            string strFilename = file.Name;
            byte[] binFile = file.OpenBinary();
 
            foreach (SPWeb web in col)
            {
                if (web.GetFolder("myDocuments").Exists)
                {
                    SPFolder folder = web.GetFolder("myDocuments");
                    web.Files.Add(strFilename, binFile, true);
                }
                web.Dispose();
            }
            web.Dispose();
            site.Dispose();
 
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return false;
        }
    }
}
Note: you should always use Dispose object if them implement IDisposable interface.

Featured pages