FileIO.AppendTextAsync is actually overwriting - c#

I'm using FileIO to append Json data in a LocalStorage file.
public static async Task AppendToJsonLocalStorage<T>(string filename, T objectToWrite) where T : new()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
}
AppendTextAsync should only add new text at the end of the existing file, wright ?
Because when I check the file in my file explorer with a text editor it's always overwriting the former text in it.

Use CreationCollisionOption.OpenIfExists instead of CreationCollisionOption.ReplaceExisting when you create the file:
StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
ReplaceExisting replaces any existing file as the name suggests. Please refer to the docs for more information.

Related

Storing and retrieving downloaded files

I have created local folder for downloading files using followling code
StorageFile destinationFile;
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var dataFolder = await local.CreateFolderAsync("AppDownloads",
CreationCollisionOption.OpenIfExists);
destinationFile = await dataFolder.CreateFileAsync(destination,
CreationCollisionOption.GenerateUniqueName);
Now i need to access all downloaded files from the sub folder created.
I have tried using:
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
IStorageFolder dataFolder1 = await local.GetFolderAsync("AppDownloads");
IEnumerable<IStorageFile> files = await local.GetFilesAsync();
But this is not working.How to get all downloaded files from this folder ?
Thank you.

Local Cache is not being able to create XML document because the document is too lare

I am currently developing a Windows 8.1 Application using C# and XAML in which I store a huge amount of data using XML format in the local cache of the application. I am getting the following error with one of the XML files out of three since the other two are being created: "Error:There was an error generating the XML document." Below is my code:
if (!string.IsNullOrEmpty(localData2))
{
StorageFile localFile = await ApplicationData.Current.LocalFolder
.CreateFileAsync("LocalCache2.xml", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(localFile,
ObjectSerializer<ObservableCollection<aceapp.Competitor>>.ToXml(cacheXML2));
}
if (!string.IsNullOrEmpty(localData3))
{
StorageFile localFile = await ApplicationData.Current.LocalFolder
.CreateFileAsync("LocalCache3.xml", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(localFile,
ObjectSerializer<ObservableCollection<aceapp.Attributes>>.ToXml(cacheXML3));
}
if (!string.IsNullOrEmpty(localData))
{
MemoryStream stream = new MemoryStream();
StorageFile localFile = await ApplicationData.Current.LocalFolder
.CreateFileAsync("LocalCache1.xml", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(localFile,
ObjectSerializer<ObservableCollection<aceapp.Sector>>.ToXml(cacheXML1));
}
The Error is with the last XML which is the largest one.
Any idea about this issue and how to fix it?

Stream image to file from SavePicker in Windows 8

I need to save Image from Local Storage Folder to file selected from SavePicker.
Should I use stream?
Here is my code:
StorageFile file = await savePicker.PickSaveFileAsync();
if (null != file)
{
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile current_photo = await localFolder.GetFileAsync(img.Tag.ToString());
// TODO Stream from current_photo to file
}
CopyAsync should do it:
await current_photo.CopyAndReplaceAsync(file);

Store image in to StorageFile from image control

how can i store image in to StorageFile from image control in windows store apps?
I'm using following link but that is not useful for me
StorageFile file = await StorageFile.CreateStreamedFileFromUriAsync(" ", new Uri(user.ProfilePicUrl), new RandomAccessStream());
http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.storagefile.createstreamedfileasync.aspx
I need clear solution for my problem. How can I do this?
You can use the following method to save an image from an url to a file in LocalFolder:
public async Task<string> DownloadFileAsync(Uri uri, string filename)
{
using (var fileStream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(filename, CreationCollisionOption.ReplaceExisting))
{
var webStream = await new HttpClient().GetStreamAsync(uri);
await webStream.CopyToAsync(fileStream);
webStream.Dispose();
}
return (await ApplicationData.Current.LocalFolder.GetFileAsync(filename)).Path;
}

Saving a stream containing an image to Local folder on Windows Phone 8

I'm currently trying to save an stream containing a jpeg image I got back from the camera to the local storage folder. The files are being created but unfortunately contain no data at all. Here is the code I'm trying to use:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteBytes(UsefulOperations.StreamToBytes(file));
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
public static class UsefulOperations
{
public static byte[] StreamToBytes(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
Any help saving files this way would be greatly appreciated - all help I have found online refer to saving text. I'm using the Windows.Storage namespace so it should work with Windows 8 too.
Your method SaveToLocalFolderAsync is working just fine. I tried it out on a Stream I passed in and it copied its complete contents as expected.
I guess it's a problem with the state of the stream that you are passing to the method. Maybe you just need to set its position to the beginning beforehand with file.Seek(0, SeekOrigin.Begin);. If that doesn't work, add that code to your question so we can help you.
Also, you could make your code much simpler. The following does exactly the same without the intermediate classes:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}

Categories