Silverlight MediaElement, choosing local disc file - c#

I'm trying to make a Media Player where you can choose either to render a file from url or local disc. I had no problem making it to open and render url file
void LoadVideo_Click(object sender, RoutedEventArgs e)
{
LoadVideo.IsEnabled = false;
mediaElement.Source = new Uri(path, UriKind.Absolute);
With string path = "http://www.blablabla.com/movie.wmv"
The problem occurs when I'm trying to specify local disc file path(as "c:\movie.wmv" or #"c:\movie.wmv"). It simply doesn't work that way.
As far as I have read, you don't have direct access to files on your hard drive besides those which already are in the project directory. What I want to do is:
use Dialog Box to choose a file to open
save the path of file into string and transfer it to MediaElement.Source
Unfortunately, I don't have a clue how to do it. I would be grateful for any advices.

Here you go, this should do the trick:
OpenFileDialog fdlg = new OpenFileDialog(); //you need to use the OpenFileDialog, otherwise Silverlight will throw a tantrum ;)
fdlg.Filter = "MP4 Files|*.mp4|AVI files|*.avi"; //set a file selection filter
if (fdlg.ShowDialog() != true) //ShowDialog returns a bool? to indicate if the user clicked OK after picking a file
return;
var stream = fdlg.File.OpenRead(); //get the file stream
//Media is a MediaElement object in XAML
Media.SetSource(stream); //bread and butter
Media.Play(); //no idea what this does
Here's an extensive example on how to use the OpenFileDialog. As for the MediaElement, you can see in the code above all you needed was the SetSource() method (as opposed to the Source property).

Related

How to open a PDF file in its associated application in a UWP application?

I have a UWP application that contains a PDF file in a folder called Images and I need to open the file in its associated application on Windows (a browser or a PDF reader). I've seen all the similar questions posted here and came to the code below but it didn't work. Any suggestion?
private async void nviHelp_Tapped(object sender, TappedRoutedEventArgs e)
{
string pdfFile = #"Images\witmnlptbr.pdf";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(pdfFile);
if (file != null)
{
var success = await Windows.System.Launcher.LaunchFileAsync(file);
}
}
The Launcher.LaunchFileAsync Method will launch the default app associated with the specified file. There are two things that you need to notice about this.
Make sure that the Build Action of the target file is set to content.
Make sure that the default app for the PDF file is set to the browser or the PDF reader in the Settings system.

How do I create a mandatory file save location with C#?

I am working with a client application that needs to have a local repository to save updates made to a group of objects, called "Books". However, I am not able to save the objects back into the SQL server until the entire book has been updated. So the powers that be have decided to use an excel file as a repository, we are calling a work list.
The user has to be able to name the work list so that it is meaningful to them, but they cannot be able to edit the work list in excel. My idea was to create a hidden folder to store the work lists, and the app can retrieve them from that location.
Here is my question:
Is there a way to keep the windows dialog box hidden, so the user cannot choose where the file is saved to, yet pass a name to the dialog for the work
list?
I am using the standard Microsoft.Win32.SaveFileDialog currently, but I can change, if I need to, in order to accomplish this task.
Here is my SaveFileDialog code, that allows the user to change the name but also the path to where the file saves:
public void SaveToFile(string BookName)
{
var file = "";
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = string.Format("{0} \\{1} Codes", WORKLIST_SAVE_PATH, BookName); // Default file name
dlg.DefaultExt = ".xlsx"; // Default file extension
dlg.Filter = " Excel Files (.xlsx)|*.xlsx"; // Filter files by extension
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Save document
file = dlg.FileName;
}
else return;
File.WriteAllText(file, Export(true));
}

C# OpenFileDialog: The filename, directory name, or volume label syntax is incorrect

I need to programmatically open a document from Sharepoint in Visio. But when I navigate to the network folder, select a document and click on open, I
get the following error:
The filename, directory name, or volume label syntax is incorrect
When searching for the error, I found the following documentation: https://msdn.microsoft.com/en-us/library/ms832054.aspx. So I guess that the file name contains illegal characters. I tried to use the FileOk event to overwrite the validation of the fileName:
public void openFile() {
OpenFileDialog sf = new OpenFileDialog();
sf.FileOk += openFileDialog_FileOk;
if (sf.ShowDialog() == DialogResult.OK)
{
var app =(Microsoft.Office.Interop.Visio.Application)context.Application;
app.Documents.Open(sf.FileName);
}
}
private void openFileDialog_FileOk(object sender, CancelEventArgs e)
{
var sfd = sender as OpenFileDialog;
var file = new FileInfo(sfd.FileName);
if (file.Name.Contains('#'))
e.Cancel = true;
}
but the event does not fire. Using the standard Visio interface it is possible to open files from Sharepoint but the file dialog looks a bit different:
How can I get a similar file dialog? And so my questions is: how can I programmatically open a Visio document from Sharepoint (network folder)?
Since Visio does not provide app.GetOpenFilename API, you are out of luck. But you could use another office application for the same. Like Excel for example:
var excel = new Excel.Application();
var fileName = excel.GetOpenFilename();
excel.Quit();
var visio = new Visio.Application();
visio.Documents.Open(fileName);
which provides a "similar dialog" and "normal url", that is understood by Visio API without any issues.
The problem probably is that Visio API does not understand UNC DAV file path format with #SSL part, that is provided by the default "built-in" OpenFileDialog (or may be something else as well). Check what is the value of the .FileName returned by the default dialog. BTW, to prevent error messages, it's enough to set sf.CheckFileExists = false, maybe that will be enough.

How to display an image from a network folder or local drive in a Windows Universal App

I'm having trouble displaying an jpg in an Image control in a Windows Universal App. (I had the same problem trying to create a Windows 8 Store app as well)
I have a simple form with an Image control on it. All I want to do is be able to open images in a folder on my local drive or a network drive on my local network and display them. But I am not having any luck. The only thing I get is E_NETWORK_ERROR, with no additional information.
I assume it probably has something to do with security, but surely there must be a setting or permission to allow me to do it. I tried enabling Private Networks in the Capabilities tab of the manifest, but that didn't help. I don't see anything in Declarations that sounds like what I need.
I know UWP apps are somewhat sandboxed, but if you can't even access local files, what good are they?
Here is a sample of code I have tried. I've done other iterations as well, but they all have the same end result.
Xaml:
<Image Name="Image1"/>
Code behind:
public LoadImage()
{
var bitmap = new BitmapImage();
bitmap.ImageFailed += Bitmap_ImageFailed;
bitmap.UriSource = new Uri(#"D:\Users\Steve\Documents\SomeImage.JPG", UriKind.Absolute);
Image1.Source = bitmap;
}
private void Bitmap_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
Debug.Write(e.ErrorMessage);
}
When I run it, I end up in the Bitmap_ImageFailed event and the ErrorMessage property is simply "E_NETWORK_ERROR", and nothing is displayed in the Image. Not very helpful.
What am I missing? It has to be something simple and obvious that I am overlooking.
Update:
Thanks to all the suggestions here I was able to get it going. The part I was failing to get through my skull was that you can't just give it a folder and expect it to read a file, even as a "quick & dirty test". You have to go through "proper channels" to get there. I pieced it all together and came up with this example which displays the first image in the selected folder:
private async void Button_Click(object sender, RoutedEventArgs e)
{
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add(".jpg");
folderPicker.FileTypeFilter.Add(".tif");
folderPicker.FileTypeFilter.Add(".png");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
var files = await folder.GetFilesAsync();
var bitmap = new BitmapImage();
bitmap.ImageFailed += Bitmap_ImageFailed;
var stream = await files.First().OpenReadAsync();
await bitmap.SetSourceAsync(stream);
Image1.Source = bitmap;
}
}
In addition, I had to add the file types for .jpg, .tif and .png as well as File Open Picker to the Declarations.
You can figure out all necessary information in MSDN article File access permissions
In addition to the default locations, an app can access additional files and folders by declaring capabilities in the app manifest (see App capability declarations), or by calling a file picker to let the user pick files and folders for the app to access (see Open files and folders with a picker).
So if you want to read a file from users document folder you need to update your applications AppXManifest to request the Document Library Access capability.
You also need to update your AppXManifest by declaring what file type(s) you want to access. Then, even with access to the folders, you only have access to a limited set of file types. You have to specify supported files types on Declarations tab
I set a new file type (.txt) and let it role from there. And code example
async void Button_Click_2(object sender, RoutedEventArgs e)
{
var _Name = "HelloWorld.txt";
var _Folder = KnownFolders.DocumentsLibrary;
var _Option = Windows.Storage.CreationCollisionOption.ReplaceExisting;
// create file
var _File = await _Folder.CreateFileAsync(_Name, _Option);
// write content
var _WriteThis = "Hello world!";
await Windows.Storage.FileIO.WriteTextAsync(_File, _WriteThis);
// acquire file
try { _File = await _Folder.GetFileAsync(_Name); }
catch (FileNotFoundException) { /* TODO */ }
// read content
var _Content = await FileIO.ReadTextAsync(_File);
await new Windows.UI.Popups.MessageDialog(_Content).ShowAsync();
}

Writing a JSON (or TXT) file in WPF C#

I have been trying to make sense of this http://msdn.microsoft.com/en-us/library/sfezx97z.aspx which uses the SaveFileDialog, but it is hard for me to understand. I have the following code:
FileInfo existingFile = new FileInfo("C:\\Users\\cle1394\\Desktop\\Apple Foreign Tax Payment Sample Layout Proposed - Sample Data.xlsx");
ConsoleApplication2.Program.ExcelData data = ConsoleApplication2.Program.GetExcelData(existingFile);
var json = new JavaScriptSerializer().Serialize(data);
How can I output the contents of json to a .json or .txt file?
I would like to let the user either see a link/ button to click to download/ save the file to a location on their computer, or, simply display the save file dialog box so that they can save the file to a location on their computer.
EDIT (to let OP comment on what parts are not clear):
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.ShowDialog();
if(saveFileDialog1.FileName != "")
{
File.WriteAllText(saveFileDialog1.FileName,json);
}
You are looking for this, then:
File.WriteAllText(#"c:\some\path\json.txt",json);
And note that it will save the file using UTF8-encoding without a Byte Order Mark. If you need the BOM, you need to use the File.WriteAllText(path, content, Enconding);
See here.
Update - adding sample with SaveFileDialog:
if(!string.IsNullOrEmpty(saveFileDialog.FileName))
{
//saveFileDialog.FileName should contain the full path
//according to the documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filename.aspx
File.WriteAllText(saveFileDialog.FileName,json);
}

Categories

Resources