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.
Related
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:
I have a situation where my file changes sizes (things added and deleted frequently). The user has the option to save their file. However, if they save their file OVER an existing file that is larger (which they are allowed to do), then it scrambles the file by leaving extra crud at the end from the file that was larger.
For example, I have the following code:
// The user saves their data to disk. No problem.
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
savePicker.SuggestedFileName = "New Document";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
using (var stream = await file.OpenStreamForWriteAsync())
{
using (var sw = new StreamWriter(stream))
{
sw.Write("ABCDEFGH");
}
}
}
// The user saves their data to disk again, overwriting their first file.
FileSavePicker savePicker2 = new FileSavePicker();
savePicker2.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker2.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
savePicker2.SuggestedFileName = "New Document";
StorageFile file2 = await savePicker2.PickSaveFileAsync();
if (file2 != null)
{
using (var stream = await file2.OpenStreamForWriteAsync())
{
using (var sw = new StreamWriter(stream))
{
sw.Write("1234");
}
}
}
}
When this code is finished, my resulting file is 1234EFGH, not 1234, as I had expected.
What am I doing wrong? I can't just delete the file between the two calls or the StorageFile will crash on OpenStreamAForWriteAsync(...)
To cut tail of the stream if you overwriting the existing file adjust length of the stream to match last position (make sure to flush stream/writer before updating length):
stream.SetLength(stream.Position);
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
I see solution for this problem:
Saving as jpeg from memorystream in c#
but it does not work in winRT.
Is there a simple way to save MemoryStream as JPEG using FileSavePicker?
I tried:
private async void Save_Image(MemoryStream image)
{
// Launch file picker
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("JPeg", new List<string>() { ".jpg", ".jpeg" });
StorageFile file = await picker.PickSaveFileAsync();
if (file == null)
return;
Stream x = await file.OpenStreamForWriteAsync();
image.WriteTo(x)
}
but it is saving blank file. May be I am doing something wrong.
Tried one more approach but again blank image:
private async void Save_Image(MemoryStream image)
{
// Launch file picker
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("JPeg", new List<string>() { ".jpg", ".jpeg" });
StorageFile file = await picker.PickSaveFileAsync();
if (file == null)
return;
int end = (int)image.Length;
byte[] buffer = new byte[end];
await image.ReadAsync(buffer, 0, end);
await FileIO.WriteBytesAsync(file, buffer);
}
Got it! It was the seeking position I was missing and also the "using". Had to set it externally to 0.
Here is the code:
private async void Save_Image(MemoryStream image)
{
// Launch file picker
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("JPeg", new List<string>() { ".jpg", ".jpeg" });
StorageFile file = await picker.PickSaveFileAsync();
if (file == null)
return;
using (Stream x = await file.OpenStreamForWriteAsync())
{
x.Seek(0, SeekOrigin.Begin);
image.WriteTo(x);
}
}
I'm trying to append to a file in the latest Windows Phone. The problem is i'm trying to do everything asynchronously and i'm not sure how to do it.
private async void writeResult(double lat, double lng)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync("result.txt", CreationCollisionOption.OpenIfExists);
Stream writeStream = await storageFile.OpenStreamForWriteAsync();
using (StreamWriter writer = new StreamWriter(writeStream))
//using (StreamWriter sw = new StreamWriter("result.txt", true))
{
{
await writer.WriteLineAsync(lat + "," + lng);
//await sw.WriteLineAsync(lat + "," + lng);
writer.Close();
//sw.Close();
}
}
}
I have this so far, which writes to the file fine and I can read it later on much the same, however it writes over what I have instead of on a new line. The commented out lines show how to go about without the stream in WP7, but I can't get that to work either (the true is is the append flag) and really should be utilizing the new WP8 methods anyway.
Any comments appreciated
Easier way:
await Windows.Storage.FileIO.AppendTextAsync(storageFile, "Hello");
I used this code, works for me
private async System.Threading.Tasks.Task WriteToFile()
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes("Some Data to write\n".ToCharArray());
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name DataFolder.
var dataFolder = await local.CreateFolderAsync("DataFolder",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("DataFile.txt",
CreationCollisionOption.OpenIfExists);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Seek(0, SeekOrigin.End);
s.Write(fileBytes, 0, fileBytes.Length);
}
}
I was able to use the suggestion ( Stream.Seek() ) by Oleh Nechytailo successfully