Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Here is the code

private void downloadList(SPObjectData objectData)
    {
        using (SPWeb currentWeb = objectData.Web)
        {
            foreach (SPList list in currentWeb.Lists)
            {
                    foreach (SPFolder oFolder in list.Folders)
                    {
                        if (oFolder != null)
                        {
                            foreach (SPFile file in oFolder.files)
                            {
                                if (CreateDirectoryStructure(tbDirectory.Text, file.Url))
                                {
                                    var filepath = System.IO.Path.Combine(tbDirectory.Text, file.Url);
                                    byte[] binFile = file.OpenBinary();
                                    System.IO.FileStream fstream = System.IO.File.Create(filepath);
                                    fstream.Write(binFile, 0, binFile.Length);
                                    fstream.Close();
                                }
                            }
                        }
                }
            }
        }
    }

Error while compilation

Error Unable to cast object of type 'Microsoft.SharePoint.SPListItem' to type 'Microsoft.SharePoint.SPFolder'.

Error coming on line " foreach (SPFolder oFolder in list.Folders)

I am trying to assign a folder in list. folders to folder but for some reason it giving error mentioned above.

share|improve this question
    
Check this link for answer stackoverflow.com/questions/8657442/… –  Muhammad Raja Dec 28 '11 at 15:48

1 Answer 1

up vote 4 down vote accepted

The SPList.Folders returns the collection of SPListItem object. so we have to iterate the SPList.Items and then we have get the folder object from SPListItem.

We have to replace the following line,

foreach (SPFolder oFolder in list.Folders)

with this snippet.

foreach (SPListItem item in list.items)
{
   SPFolder oFolder = item.Folder;
   // Your code
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.