File Uploading in Silverlight - silverlight

I want to upload a particular file on server in Silverlight 4,
Simply, to upload any file we can use the "Browse" button.
When you click on this button we can get the file directory and choose any file & we can upload the particular file.
i have coded on browse button
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var fileDialog =new OpenFileDialog();
fileDialog.ShowDialog();
fileDialog.Multiselect = true;
txtUploader.Text = fileDialog.File.DirectoryName;
fileDialog.File.CopyTo("C:/UploadedFiles");
}
here the problem is, only the dialog box is opening
not able to select multiple file,
not getting path,
not able to upload the file to specified location.

Try changing the order that you are setting up your OpenFileDialog Box.
Also you are returning a FileInfo object. If you are going to return multiple files you need use Files instead of File it will return a collection of FileInfo objects. You can then iterate over the collection to get your information. In testing out the code I was getting a Security Exception on reading the path of the files, you do not have the permissions needed to do what you want to do per #MattGreer's comment.
Edit added from #AnthonyWJones comment.
There is not any way to do what you are trying to do, except to create an OOB with elevated trust, and that will limit you to the users MyDocuments Folder.
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var fileDialog =new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.ShowDialog();
IEnumerable<System.IO.FileInfo> files = fileDialog.Files;
foreach (System.IO.FileInfo fi in files)
{
txtUploader.Text = fi.DirectoryName;
fi.CopyTo("C:/UploadedFiles");
}
}

Related

Why I cannot Navigate the html file by using WebView inside of the App in Wpf?

I make a Wpf projcect which demos how to use WebView to Navigate a html file inside of the App, but fails.
The main cs file code is below:
public MainWindow()
{
this.InitializeComponent();
this.wv.ScriptNotify += Wv_ScriptNotify;
this.Loaded += MainPage_Loaded;
}
private async void Wv_ScriptNotify(object sender, Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT.WebViewControlScriptNotifyEventArgs e)
{
//await (new MessageDialog(e.Value)).ShowAsync();
textBlock.Text = e.Value;
//返回结果给html页面
await this.wv.InvokeScriptAsync("recieve", new[] { "hehe, 我是个结果" });
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
//我们事先写好了一个本地html页面用来做测试
this.wv.Source = new Uri("ms-appx-web://Assets/index.html");
//this.wv.Source = new Uri("http://www.baidu.com");
}
And the html file index.html is inside of the project, located at Assets/index.html. Its source code is here:
https://github.com/tomxue/WebViewIssueInWpf/raw/master/WpfApp3/Assets/index.html
I put the project code onto GitHub: https://github.com/tomxue/WebViewIssueInWpf.git
If the project works well, when WebView visits the inner html file, it should show a button at first.
But I saw nothing.
More:
According to the accepted answer(Thank to Pavel Anikhouski), I changed my code as below and it now works.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
//我们事先写好了一个本地html页面用来做测试
//this.wv.Source = new Uri("ms-appx-web://Assets/index.html");
//this.wv.Source = new Uri("http://www.baidu.com");
var html = File.ReadAllText("../../Assets\\index.html");
wv.NavigateToString(html);
}
It seems to be a known issue with WebView control in WindowsCommunityToolkit
You can use only absolute URIs to resources in members of the WebView control that accept string paths.
WebView controls don't recognize the ms-appx:/// prefix, so they can't read from the package (if you've created a package for your
application).
WebView controls don't recognize the File:// prefix. If you want to read a file into a WebView control, add code to your application that
reads the content of the file. Then, serialize that content into a
string, and call the NavigateToString(String) method of the WebView
control.
So, instead of loading a file this.wv.Source = new Uri("ms-appx-web://Assets/index.html"); try to read a local file and then navigate to the string
var html = File.ReadAllText("Assets\\index.html");
this.wv.NavigateToString(html);
It should work fine (I've seen the button and message at my end). Also, don't forget to copy Assets\index.html to the output directory (set Copy Always or Copy if newer)

Silverlight OpenFileDialog Filter Property with Extension and file name

Is there any way when set the filter property of OpenFileDialog control in Silverlight, we can filter file by extension and part of the file name? For example how do I set the filter property if i just want to show files that starts with letter A and have the extension .dat. Please keep in mind i might have other files with same extension by starts with different letter. I don't want to show those. Thanks for your reply.
Well very old question, but i had similar problem and here is how it worked for me:
private void BrowseExcelFileButton_Click(object sender, RoutedEventArgs e)
{
//This needs to be before try statement othervise exception is thrown ("Dialogs must be user-initiated")
OpenFileDialog openFileDialog = new OpenFileDialog();
try
{
openFileDialog.Filter = "Excel Files (*.xls,*.xlsx)|*.xls;*.xlsx|All Files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == true)
{
...
}
}
catch (Exception ex)
{
...
}
}

Sharepoint 2010 Upload file using Silverlight 4.0

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
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.)

How do I extract zip file in Windows Phone 7?

I have a zip file in my Windows Phone 7 project. I have set the Build Action to Content and Copy to output directory to Always. The zip file contains the folder structure. I want this to be copied entirely as it is in my Phone Project. I am using SharpZipLib for this. This is the code :-
Stream stremInfo = Application.GetResourceStream(new Uri("xip.zip", UriKind.Relative)).Stream;
new FastZip(). ExtractZip(stremInfo,
"",FastZip.Overwrite.Always,null,null,null,true,true);
However I get error when ExractZip is called. The exception I get is "MethodAccessException". Cannot call GetFullPath(). Can anybody let me know what am I missing? What can I do to avoid it?
You dont need to use another library if you know what files you want out of the Zip. You can use the App.GetResourceStream phone API to reach into the Zip and get the file.
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("http://www.foo.com/pictures.zip"));
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamResourceInfo info = new StreamResourceInfo(e.Result,"");
StreamResourceInfo pic = App.GetResourceStream(info, new Uri("IMG_1001.jpg", UriKind.Relative));
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(pic.Stream);
img.Source = bitmap;
}
For more informaiton on reading the list of files from th Zip check out this blog post.
Check out this utility, it may help you out.
http://www.sharpgis.net/post/2009/04/22/REALLY-small-unzip-utility-for-Silverlight.aspx
I've used the SL port of the SharpZipLib to do this - see http://slsharpziplib.codeplex.com/
There's lots of example code available for how to use it - and a good quickstart in their source - http://slsharpziplib.codeplex.com/SourceControl/changeset/view/75568#1416103

How to stop WPF drag and drop from locking dropped file

I have a drag and drop application (which allows users to organize their files) that takes files. The app keeps a list of strings that corresponds to the files, but it does not need access to the files themselves. The problem is that the program locks files like the application has them open. How can I release them?
private void File_Dropped(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent(DataFormats.FileDrop))
return;
var files = e.Data.GetData(DataFormats.FileDrop, true) as string[];
ImageFile iFile;
foreach (var file in files)
{
if (_Extensions.Contains(IO.Path.GetExtension(file).ToUpper()))
{
iFile = new ExtendedImageFile(new StringBuilder(file).ToString());
LBXFiles.Items.Add(iFile);
}
}
e.Handled = true;
}
Fantastic fix lived up to his name. See the commend on the original post

Resources