Thursday, 26 June 2014

spFile.OpenBinary() error : file could not be opened

Are you facing this problem while opening the spfile using the url..?
SPFile spFile = web.GetFile("/Document Library Name/" + FileName+ ".jpg");
byte[] binFile = spFile.OpenBinary();  <----- error that file could not be opened
Here is the solution.
Get the SPListItem that contains your file.
Use CAML Query to get the list item by passing the column name and its value.
    SPList list= web.Lists["Document Library Name"];
    SPQuery query = new SPQuery();
    query.Query = "<Where><Eq><FieldRef Name=\"" + columnName + "\"/><Value Type=\"Text\">" + value + "</Value></Eq></Where>";
    SPListItemCollection itmColl = SPListItemCollection itmcol = list.GetItems(query);
    SPFile picture=null;
    if (itmcol.Count > 0)
     {
        picture = itmcol[0].File;
        //byte[] binFile = spFile.OpenBinary();
     }
     byte[] fileData = picture.OpenBinary();