Hitesh
Hitesh

Reputation: 1228

How to open a file from silverlight folder

I have a xlsx file (New.xlsx) in a folder (Common) in my project (Silverlight side).

I want to access that file path on button click event and want to open that file.

I used below path :

string path = @"/Common/New.xlsx";
string path1 = excel.Workbooks.Open(path);
excel.Visible = true;

But it is not working and I cannot open that file.

How to access file using file path in Silverlight?

Upvotes: 2

Views: 843

Answers (2)

Nkosi
Nkosi

Reputation: 247018

You have a few options available to you for giving access to the file in question.

  • You can get the content of the file as a stream and then ask the user to save the file via the SaveFileDialog class. The user would then have to select where they want to save the file and then open it manually.
public static byte[] GetBytesFromStream(Stream input){
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream()){
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0){
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

public void OnButtonClick(){
    var templateUri = new Uri("/Common/New.xlsx, UriKind.Relative");
    var templateStream = Application.GetResourceStream(templateUri).Stream;
    var bytes = GetBytesFromStream(templateStream);
    var sfd = new SaveFileDialog() {
            DefaultExt = "xlsx",
            Filter = "Excel Files (*.xlsx)|*.xlsx|All files(*.*)|*.*",
            FilterIndex = 1                
    };

    if (sfd.ShowDialog() == true) {
        using (Stream stream = sfd.OpenFile()) {
            stream.Write(bytes, 0, bytes.Length);
        }
    }
}
  • You can have the file stored server side and when the user clicks the button you tell the browser to get he file in question. The browser will then take over and ask the user if they want to save the file to disk or open using a known application.
public void OnButtonClick(){
    string link = "{the url/endpoint to the file on the server}";
    System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(link), "_blank");
}
  • You can go down the AutomationFactory route but that would require alot of configuration changes like suggested here

I think it's much better to have such things on the server rather than on the client side. The server is more well equipped to handle such processing.

Upvotes: 3

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

Try the following:

var TemplateUri = new Uri("/Common/New.xlsx, UriKind.Relative");
var stream = Application.GetResourceStream(sheetUri).Stream;

The file is deployed witin the xap file (which is a zip file) and cannot be handled by a normal file on the disk.

It is not clear for me what Excel library you are using, but it should allow you to load data from Stream.

Upvotes: 2

Related Questions