How to: Access, Copy, and Move Files

Applies to: SharePoint Foundation 2010

Available in SharePoint Online

To retrieve files and folders from a Web site, use the GetFile() or GetFolder() method of the SPWeb class.

You can use the GetFolder method of the SPWeb class to return a specified folder. Then you can access individual files in the folder. After instantiating an SPWeb object (for example, as oWebsite), use SPFolder oFolder = oWebsite.GetFolder("Shared Documents") (in Microsoft Visual Basic, use Dim oFolder As SPFolder = oWebsite.GetFolder("Shared Documents")) to return the Shared Documents folder for the site.

Example

The following example returns the collection of files in the folder and displays information about the files.

Using oWebsite As SPWeb = New SPSite("https://Server/sites/SiteCollection").OpenWeb()
    Dim folderUrl As String = "/Shared Documents/MySubFolder"
    Dim oFolder As SPFolder = oWebsite.GetFolder(folderUrl)
    Dim collFile As SPFileCollection = oFolder.Files
    
    For Each oFile As SPFile In collFile
        Label1.Text += ("<BR>Url: " & oFile.Url.ToString() & " Size: ") + oFile.Length.ToString()
    Next
End Using
using (SPWeb oWebsite = new SPSite("https://Server/sites/SiteCollection").OpenWeb())
{
    string folderUrl = "/Shared Documents/MySubFolder";
    SPFolder oFolder = oWebsite.GetFolder(folderUrl);
    SPFileCollection collFile = oFolder.Files;

    foreach (SPFile oFile in collFile)
    {
        Label1.Text += "<BR>Url: " + oFile.Url.ToString() + " Size: " + oFile.Length.ToString();
    } 
}

The previous example lists the URL and size of every file within Shared Documents.

The example requires a using directive (Imports inVisual Basic) for the Microsoft.SharePoint namespace.

You can load files into a generic List<T> object to enumerate a collection. The following example moves all files from the Shared Documents list of the current site to a subfolder named StorageFolder, overwriting any file of the same name that is located in the folder.

Dim oWebsite As SPWeb = SPContext.Current.Web
Dim oFolder As SPFolder = oWebsite.GetFolder("Shared Documents")
Dim collFile As SPFileCollection = oFolder.Files

'Copy the files to a generic List of type SPFile
Dim listFiles As New List(Of SPFile)(collFile.Count)
For Each oFile As SPFile In collFile
    listFiles.Add(oFile)
Next

' Enumerate the List and move the files into the subfolder.
For Each moveFile As SPFile In listFiles
    moveFile.MoveTo("Shared Documents/StorageFolder/" & moveFile.Name, True)
Next
SPWeb oWebsite = SPContext.Current.Web;
SPFolder oFolder = oWebsite.GetFolder("Shared Documents");
SPFileCollection collFile = oFolder.Files;

/*Copy the files to a generic List of type SPFile*/
List<SPFile> listFiles = new List<SPFile>(collFile.Count);

foreach (SPFile oFile in collFile)
{
    listFiles.Add(oFile);
}

/* Enumerate the List and move the files into the subfolder.*/
foreach (SPFile moveFile in listFiles)
{
    moveFile.MoveTo("Shared Documents/StorageFolder/" + moveFile.Name, true);
}

The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint and System.Collections.Generic namespaces.

To copy files from one location to another, use one of the CopyTo() methods of the SPFile class. The following example enumerates all the folders and files in a document library and copies them to another document library. The Button_Click event handler iterates through all the files in the top-level folder, listing the name and size (in kilobytes) of each file that exceeds a multiple of the value that is specified in a text box by the user, and then calls the CopyToTarget method to copy the file to a specified folder. The EnumerateFolder method then recursively iterates through all the subfolders and passes each file collection to the CopyToTarget method. The example assumes the existence of a button, a label, and three text boxes to specify a file size, source folder, and target folder for the operation.

Private oWebsite As SPWeb

Protected Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim fromFolder As String = TextBox3.Text
    
    Dim oFolder As SPFolder = oWebsite.GetFolder(fromFolder)
    Dim collFile As SPFileCollection = oFolder.Files
    
    CopyToTarget(collFile)
    
    Dim collFolder As SPFolderCollection = oFolder.SubFolders
    
    EnumerateFolders(collFolder)
End Sub

Private Sub CopyToTarget(ByVal copyFiles As SPFileCollection)
    Dim mySize As String = TextBox1.Text
    Dim toFolder As String = TextBox2.Text
    
    Dim maxLength As Integer = Convert.ToInt32(mySize)
    
    For Each oFile As SPFile In copyFiles
        If oFile.Length > maxLength * 1024 Then
            Label1.Text += (SPEncode.HtmlEncode(oFile.Name) & ": ") + oFile.Length /1024 & "kb<BR>"
            oFile.CopyTo((toFolder & "/") + oFile.Name, True)
        End If
    Next
End Sub

Private Sub EnumerateFolders(ByVal copyFolders As SPFolderCollection)
    For Each subFolder As SPFolder In copyFolders
        If subFolder.Name <> "Forms" Then
            Dim subFiles As SPFileCollection = subFolder.Files
            
            CopyToTarget(subFiles)
        End If
        
        Dim subFolders As SPFolderCollection = subFolder.SubFolders
        
        EnumerateFolders(subFolders)
    Next
End Sub
private SPWeb oWebsite;

protected void Button_Click(object sender, EventArgs e)
{
    string fromFolder = TextBox3.Text;
            
    SPFolder oFolder = oWebsite.GetFolder(fromFolder);
    SPFileCollection collFile = oFolder.Files;

    CopyToTarget(collFile);

    SPFolderCollection collFolder = oFolder.SubFolders;

    EnumerateFolders(collFolder);
}

private void CopyToTarget(SPFileCollection copyFiles)
{
    string mySize = TextBox1.Text;
    string toFolder = TextBox2.Text;

    int maxLength = Convert.ToInt32(mySize);

    foreach (SPFile oFile in copyFiles)
    {
        if (oFile.Length > maxLength * 1024)
        {
            Label1.Text += SPEncode.HtmlEncode(oFile.Name) + ": " + oFile.Length / 1024 + "kb<BR>";
            oFile.CopyTo(toFolder + "/" + oFile.Name, true);
        }
    }
}

private void EnumerateFolders(SPFolderCollection copyFolders)
{
    foreach (SPFolder subFolder in copyFolders)
    {
        if (subFolder.Name != "Forms")
        {
            SPFileCollection subFiles = subFolder.Files;

            CopyToTarget(subFiles);
        }
                
        SPFolderCollection subFolders = subFolder.SubFolders;

        EnumerateFolders(subFolders);
    }
}

In this example, the CopyTo method uses two parameters, one that specifies the destination URL for the file that is copied, and the other parameter is a Boolean value that specifies whether to overwrite any file of the same name that is located at the destination.

The previous example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

See Also

Reference

Microsoft.SharePoint

Concepts

Working with List Objects and Collections

Using Visual Studio for SharePoint Development

Security Validation and Making Posts to Update Data

Elevation of Privilege