我的项目(Silverlight端)的文件夹(公用)中有一个xlsx文件(New.xlsx)。
我想在按钮单击事件中访问该文件路径,并想打开该文件。
我用下面的路径:
string path = @"/Common/New.xlsx";
string path1 = excel.Workbooks.Open(path);
excel.Visible = true;
但是它不起作用,我无法打开该文件。
如何在Silverlight中使用文件路径访问文件?
最佳答案
您可以通过一些选项来访问相关文件。
您可以将文件的内容作为流获取,然后通过SaveFileDialog
类要求用户保存文件。然后,用户将不得不选择他们想要保存文件的位置,然后手动打开它。
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);
}
}
}
您可以将文件存储在服务器端,当用户单击按钮时,您告诉浏览器获取有问题的文件。然后,浏览器将接管并询问用户是否要将文件保存到磁盘或使用已知的应用程序打开。
public void OnButtonClick(){
string link = "{the url/endpoint to the file on the server}";
System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(link), "_blank");
}
您可以沿着
AutomationFactory
路线走,但这需要进行很多配置更改,例如建议的here我认为在服务器上而不是在客户端上拥有这样的东西要好得多。服务器设备更完善,可以处理此类处理。