Work with SPFile

Represents a file in a SharePoint Web site that can be a Web Part Page, an item in a document library, or a file in a folder. Available in sandbox solution.

(1) Use the GetFile or GetFileAsString method of the SPWeb class to return a single file object;

SPWeb.GetFile() à return single file object
SPWeb.GetFileAsString()
à return single file object

(2) Use the Files property of either the SPWeb or SPFolder class to return an SPFileCollection object that represents the collection of files for a site or folder. Use an indexer to return a single file from the collection. For example, if the collection is assigned to a variable named collFiles, use collFiles[index] in C#, or collFiles(index) in Visual Basic, where index is the index number of the file in the collection, the file name including extension, or a Web site relative, site collection relative, or absolute URL.

SPWeb.Files à return SPFileCollection; SPFileCollectionVar [Index] à reutrn file name and path
SPFolder.Files à return SPFIleCollection; ; SPFileCollectionVar [Index] à reutrn file name and path

This example adds a file from the document library of one site to the Shared Documents document library of another site and its subsites.

——————————————————————————————————————————————————-

SPSite oSiteCollection = SPContext.Current.Site;

SPWeb oWebsiteSrc = oSiteCollection.AllWebs["Source_Site_Name"];

SPWebCollection collWebsites =

oSiteCollection.AllWebs["Destination_Site_Name"].Webs;

 

SPFile oFile = oWebsiteSrc.GetFile(“Source_Folder_Name/Source_File”);

string strFilename = oFile.Name;

byte[] binFile = oFile.OpenBinary();

 

foreach (SPWeb oWebsite in collWebsites)

{


if (oWebsite.GetFolder(“Shared Documents”).Exists)

{

SPFolder oFolder = oWebsite.GetFolder(“Shared Documents”);

oFolder.Files.Add(strFilename, binFile, true);

}

oWebsite.Dispose();

}

oWebsiteSrc.Dispose();


 

About these ads
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: