I have a UWP Desktop application that has text and audio files associated, for example when the user selects the Class1.txt file, the application automatically tries to open the Class1.mp3 file.
Even with broadFileSystemAccess configured, the operation always returns an access denied error.
Any help is most welcome. Thanks.
private async void nviOpen_Tapped(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".txt");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
try
{
using (var txtStream = await file.OpenStreamForReadAsync())
{
var encoding = FileEncoding.DetectFileEncoding(txtStream);
txtStream.Seek(0, SeekOrigin.Begin);
var stmReader = new StreamReader(txtStream, encoding);
var txtContent = await stmReader.ReadToEndAsync();
tbxOriginalText.Text = txtContent;
}
//Open associated audio file
var audioFile = await StorageFile.GetFileFromPathAsync(file.Path + #"\" + file.DisplayName + ".mp3");
if (audioFile != null)
{
MediaPlaybackItem mediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(audioFile));
}
}
catch (Exception ex)
{
MessageDialog msgDlg = new MessageDialog(ex.Message);
await msgDlg.ShowAsync();
}
}
}
Please take a look at the file system privacy setting and make sure that you've allowed your app for accessing your file system.
Like this:
Related
I'm working on a UWP TTS (Text to Speech) application and I'm having trouble saving speech to a file, preferably in Mp3 format. Does anyone know how to do this? In WPF, I used NAUDIO and NAUDIO.LAME, but unfortunately this does not seem to support UWP. I think I have to use Windows.Media.Transcoding API, but I didn't find any examples of how to do that. I found the code below in an article on MSDN, but it is not correct.
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
try
{
SpeechSynthesisStream stream = await WCSVariables.Synthesizer.SynthesizeTextToStreamAsync(rtbText.Text);
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(file, buffer);
}
}
catch (Exception ex)
{
MessageDialog msgdlg = new MessageDialog(ex.Message);
msgdlg.ShowAsync();
}
********** UPDATE **********
After adding capabilities and file type associations for TXT and MP3, I was able to save the TXT files in any folder, but the MP3 files do not have the correct format. Files are created but do not play audio.
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("Mp3 Audio File", new List<string>() { ".mp3" });
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
savePicker.SuggestedFileName = "New Document";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
try
{
if (file.FileType == ".txt")
{
await FileIO.WriteTextAsync(file, rtbText.Text);
}
else
{
string path = file.Path.Remove(file.Path.IndexOf(file.Name), file.Name.Length);
StorageFolder mp3Folder = await StorageFolder.GetFolderFromPathAsync(path);
StorageFile mp3File = await mp3Folder.CreateFileAsync(file.Name, CreationCollisionOption.ReplaceExisting);
SpeechSynthesisStream stream = await WCSVariables.Synthesizer.SynthesizeTextToStreamAsync(rtbText.Text);
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(mp3File, buffer);
}
}
}
catch (Exception ex)
{
MessageDialog msgdlg = new MessageDialog(ex.Message);
msgdlg.ShowAsync();
}
}
You can first create a .mp3 file and then generate a speech audio stream from a basic text string. After that, write the stream to the file.
StorageFolder folder = KnownFolders.VideosLibrary;
StorageFile file = await folder.CreateFileAsync("MyVideo.mp3",CreationCollisionOption.ReplaceExisting);
if (file != null)
{
try
{
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(file, buffer);
}
}
catch {}
}
I need to copy an image from my windows universal app, I was able to pick an image from my gallery but i don't how to copy it in another folder.
Although I was able to display the image in my UWP interface, so I think that I succeed to get it as a stream.
Any help would be appreciated, I'm lost here ... here is the code I used:
public MainPage()
{
this.InitializeComponent();
// Scenario4WriteableBitmap = new WriteableBitmap((int)Scenario4ImageContainer.Width, (int)Scenario4ImageContainer.Height);
Scenario2DecodePixelHeight.Text = "100";
Scenario2DecodePixelWidth.Text = "100";
}
private async void buttonUpload_Click(object sender, RoutedEventArgs e)
{
int decodePixelHeight=150;
int decodePixelWidth=150;
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelHeight.Text, out decodePixelHeight))
{
Scenario2DecodePixelHeight.Text = "100";
decodePixelHeight = 100;
}
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelWidth.Text, out decodePixelWidth))
{
Scenario2DecodePixelWidth.Text = "100";
decodePixelWidth = 100;
}
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelHeight = decodePixelHeight;
bitmapImage.DecodePixelWidth = decodePixelWidth;
await bitmapImage.SetSourceAsync(fileStream);
Scenario2Image.Source = bitmapImage;
}
}
}
private async void submit_Click(object sender, RoutedEventArgs e)
{
String url = "http://localhost/mydatabase/add.php";
var values = new List<KeyValuePair<String, String>>
{
new KeyValuePair<string, string>("UserName",UserName.Text),
new KeyValuePair<string, string>("UserImage",UserImage.Text),
};
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsync(url, new FormUrlEncodedContent(values));
/*client.DefaultRequestHeaders.Add("content_type", "binary/octet_stream");
responseImage = client.PostAsync("", FileChooser.FileName);*/
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(response.StatusCode.ToString());
var dialog = new MessageDialog("added succesfully ");
await dialog.ShowAsync();
}
else
{
// problems handling here
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
catch (Exception exc)
{
// .. and understanding the error here
Debug.WriteLine(exc.ToString());
}
}
`
you can use CopyAsync of StorageFile to copy the file you get from FileOpenPicker to a specific folder.
I'm trying to save a file to the Documents folder using PickSaveFileAndContinue() method in WP 8.1 RT. Everything is happening fine except the file which gets saved is empty.
When I get the file returned from the following code in OnActivated() method, it's size is zero.
Anyone?
var database = await FileHelper.GetFileAsync(ApplicationData.Current.LocalFolder, DATABASE_NAME);
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("Database File", new List<string>() { ".db" });
savePicker.DefaultFileExtension = ".db";
savePicker.SuggestedFileName = DATABASE_NAME;
savePicker.SuggestedSaveFile = database;
After the location is picked, the following code is executed in App.xaml.cs. I tried doing this inside the same page using a ContinuationManager. But then result is same.
protected async override void OnActivated(IActivatedEventArgs args)
{
byte[] buffer = null;
if(args!=null)
{
if(args.Kind == ActivationKind.PickSaveFileContinuation)
{
var file = ((FileSavePickerContinuationEventArgs)args).File;//This is empty
using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
{
buffer = new byte[stream.Size];
using (DataReader reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(buffer);
}
}
if (file != null)
{
CachedFileManager.DeferUpdates(file);
await FileIO.WriteBytesAsync(file, buffer);
Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
}
}
}
base.OnActivated(args);
}
That's expected. PickSaveFileAndContinue doesn't know what the app wants to save. It just provides an empty StorageFile. The app can then write whatever contents it wants to save into the file.
I need to download files like ".Doc , .pdf , .xls , .Jpeg, .PNG etc" from the server and store into phone memory not to Isolated. I have search a lot but can not get any things for .doc , .pdf. I got a link Downloading and saving a file Async in Windows Phone 8
but can not work. So if any one can do this please let me know.
Thanks in advance.
I have done with FileSavePicker , here is code
public void DownloadFiles(Uri url)
{
var wc = new WebClient();
wc.OpenReadCompleted +=async (s, e) =>
{
Stream st = e.Result;
buf = ReadFully(st);
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("PDF", new List<string>() { ".pdf" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
savePicker.PickSaveFileAndContinue();
StorageFile SF = await KnownFolders.PicturesLibrary.CreateFileAsync
("Guide.pdf", CreationCollisionOption.ReplaceExisting);
var fs = await SF.OpenAsync(FileAccessMode.ReadWrite);
StorageStreamTransaction transaction = await SF.OpenTransactedWriteAsync();
DataWriter dataWriter = new DataWriter(transaction.Stream);
dataWriter.WriteBytes(buf);
transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file
await transaction.CommitAsync();
};
wc.OpenReadAsync(url);
}
public static byte[] ReadFully(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();
}
}
private async void ContinueFileOpenPicker(FileSavePickerContinuationEventArgs args)
{
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteBytesAsync(file, buf);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete)
{
Debug.WriteLine("File " + file.Name + " was saved.");
}
else
{
Debug.WriteLine("File " + file.Name + " couldn't be saved.");
}
}
else
{
Debug.WriteLine("Operation cancelled.");
}
await Windows.System.Launcher.LaunchFileAsync(file);
}
For More information Please go with this url How to continue your Windows Phone app after calling a file picker
I don't think you'll be able to directly download and store the files into the memory card as they have restricted access for security purposes. I guess Isolated Storage could be the option.
Reference
In my app user can set profile pic from device memory i.e tablet memory or desktop local drive and upload it to server.
I used file picker so that user can select one picture and set it as profile picture, but the problem is the picture is not sticking to Image element.
My code:
private async void filePicker()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
String filePath = file.Path;
System.Diagnostics.Debug.WriteLine(filePath);
Uri uri = new Uri(filePath, UriKind.Relative);
profilePicture.Source = new BitmapImage(uri);
}
}
internal bool EnsureUnsnapped()
{
// FilePicker APIs will not work if the application is in a snapped state.
// If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());
if (!unsnapped)
{
//NotifyUser("Cannot unsnap the sample.", NotifyType.StatusMessage);
}
return unsnapped;
}
the file path that I'm getting is this one
filePath=C:\Users\Prateek\Pictures\IMG_0137.JPG
I don't know what went wrong.
I am not sure if this will solve the problem, this is what I did to set my image source.
Using a bitmap image as the source to your image
BitmapImage bitmapimage = new BitmapImage();
StorageFile file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
await bitmapimage.SetSourceAsync(stream);
profilePicture.Source = bitmapImage;
I have used this code ...
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
this.textBlock.Text =
"File Path: " + file.Path + Environment.NewLine +
"File Name: " + file.Name;
try
{
var stream = await file.OpenReadAsync();
var imageSource = new BitmapImage();
await imageSource.SetSourceAsync(stream);
this.image.Source = imageSource;
}
catch (Exception ex)
{
this.textBlock.Text = ex.ToString();
}
}
else
{
this.textBlock.Text = "Operation cancelled.";
}