1
votes

I am trying to do a file upload from Silverlight(Client Object Model) to Sharepoint 2010 library.. Please see the code below..

        try{
            context = new ClientContext("http://deepu-pc/");
            web = context.Web;
            context.Load(web);
            OpenFileDialog oFileDialog = new OpenFileDialog();
            oFileDialog.FilterIndex = 1;
            oFileDialog.Multiselect = false;
            if (oFileDialog.ShowDialog().Value == true)
            {
                var localFile = new FileCreationInformation();
                localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
                localFile.Url = System.IO.Path.GetFileName(oFileDialog.File.Name);
                List docs = web.Lists.GetByTitle("Gallery");
                context.Load(docs);
                File file = docs.RootFolder.Files.Add(localFile);
                context.Load(file);
                context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
            } 
        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.ToString());
        }

But I am getting the following error

System.Security.SecurityException: File operation not permitted. Access to path '' is denied.
   at System.IO.FileSecurityState.EnsureState()
   at System.IO.FileSystemInfo.get_FullName()
   at ImageUploadSilverlight.MainPage.FileUpload_Click(Object sender, RoutedEventArgs e)

Any help would be appreciated

Thanks

Deepu

1

1 Answers

3
votes

Silverlight runs with very restricted access to the client user's filesystem. When using an open-file dialog, you can get the name of the selected file within its parent folder, the length of the file, and a stream from which to read the data in the file, but not much more than that. You can't read the full path of the file selected, and you are getting the exception because you are attempting to do precisely that.

If you want to read the entire content of the file into a byte array, you'll have to replace the line

localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);

with something like

localFile.content = ReadFully(oFileDialog.File.OpenRead());

The ReadFully method reads the entire content of a stream into a byte array. It's not a standard Silverlight method; instead it is taken from this answer. (I gave this method a quick test on Silverlight, and it appears to work.)