How to append a file, asynchronously in Windows Phone 8 - c#

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

Related

How do I write a binary file in a Windows Store App?

I'm trying to implement a StreamSocket communication and the server is now sending me a ".zip" file in byte[] chuncks. It looks like my byte[] in memory is fine (amount of bytes are the same as original .zip file in the server) but when I save those bytes in a file the unzip program says it's 'corrupted'.
I've tried several options but none of them worked for me:
1
var file = await StorageFile.CreateFileAsync();
using(var stream = await file.OpenStreamForWriteAsync())
{
stream.Write(myBytes, ...);
}
2
var file = await StorageFile.CreateFileAsync();
await FileIO.WriteBytesAsync(file, myBytes);
3
var file = await StorageFile.CreateFileAsync();
using (var fileStream = await file.OpenStreamForWriteAsync())
{
var sessionData = new MemoryStream(myBytes);
sessionData.Seek(0, SeekOrigin.Begin);
await sessionData.CopyToAsync(fileStream);
}
4
var file = await StorageFile.CreateFileAsync();
using (var writer = new BinaryWriter(await file.OpenStreamForWriteAsync())
{
writer.WriteBytes(myBytes);
}
If anyone has some new ideas please share.
Regards.

Save .mp4 to Windows Phone video library

I was wondering how I can download an MP4 video file from a URI and save it to the media library on Windows Phone 8.1.
It would be great if it worked in a Universal App - but it doesn't have to.
I found this code to save an image to the camera roll - do I go the same way about this with an *.mp4 to save it to the video library? And can I just hand off a download stream (not sure if that makes sense) to that function?
StorageFolder testFolder = await StorageFolder.GetFolderFromPathAsync(#"C:\test");
StorageFile sourceFile = await testFolder.GetFileAsync("TestImage.jpg");
StorageFile destinationFile = await KnownFolders.CameraRoll.CreateFileAsync("MyTestImage.jpg");
using (var sourceStream = await sourceFile.OpenReadAsync())
{
using (var sourceInputStream = sourceStream.GetInputStreamAt(0))
{
using (var destinationStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var destinationOutputStream = destinationStream.GetOutputStreamAt(0))
{
await RandomAccessStream.CopyAndCloseAsync(sourceInputStream, destinationStream);
}
}
}
}
So I finally figured it out, this is what my code looks like:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var file = await response.Content.ReadAsByteArrayAsync();
StorageFile destinationFile
= await KnownFolders.SavedPictures.CreateFileAsync("file.mp4",
CreationCollisionOption.ReplaceExisting);
Windows.Storage.Streams.IRandomAccessStream stream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream output = stream.GetOutputStreamAt(0);
DataWriter writer = new DataWriter(output);
writer.WriteBytes(file);
await writer.StoreAsync();
await output.FlushAsync();
}

Windows phone 8 append line to file

I have such strange problem with append line ... I'm quite new with developing for Windows phone, but I program¨m in c sharp for some time. So I tried to create file for saving users data (simple lines in txt file). I use this codes:
byte[] filebytes = System.Text.Encoding.UTF8.GetBytes("blablablabla");
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var folder = await local.CreateFolderAsync("Data", CreationCollisionOption.OpenIfExists);
var file = await folder.CreateFileAsync("data.txt", CreationCollisionOption.OpenIfExists);
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(filebytes, 0, filebytes.Length);
}
for writing to file and
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
var folder = await local.GetFolderAsync("Data");
var file = await folder.OpenStreamForReadAsync("data.txt");
using (StreamReader sr = new StreamReader(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
TextBlock.Text = line;
}
}
}
to read from it. I also tried many others possibility how to read/write to files, but all ended with the same result - all data lost, and in file was only last line. First I thought that problem will be in offset here s.Write(filebytes, 0, filebytes.Length); but in other methods it was in other way and nothing helped. Right now I have improved code, that it works, but read all data and write it all at once is not solution. Thanks for any advice.
Replace
s.Write(filebytes, 0, filebytes.Length);
With
await writer.WriteLineAsync("new entry");

How to clear a file before writing into it

I am using this code to write into my file:
private async void play_Click(object sender, RoutedEventArgs e)
{
String MyScore;
Double previousScore = 0;
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var dataFolder1 = await local.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists);
var file1 = await dataFolder1.CreateFileAsync("MyFile.txt", CreationCollisionOption.OpenIfExists);
var file = await dataFolder1.OpenStreamForReadAsync("MyFile.txt");
using (StreamReader streamReader = new StreamReader(file))
{
MyScore = streamReader.ReadToEnd();
}
if (MyScore != null && !MyScore.Equals(""))
{
previousScore = Convert.ToDouble(MyScore);
}
Double CurerentScore = 0;
Double Total = 0;
String scoreText = this.ScoreTB.Text;
CurerentScore = Convert.ToDouble(scoreText);
Total = previousScore - CurerentScore;
using (var s = await file1.OpenStreamForWriteAsync())
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
s.Write(fileBytes, 0, fileBytes.Length);
}
}
But before writing into it, I want that my file should get cleared. What should I do?
This is what i have tried so far but the problem is that it writes the file up to the filebytes.length and due to that if the new information to be writed in file is less in terms of length in comparison to the privous length then some garbage value or unnecessay thing comes after the end of the new file
You can use this snippet :
var folder = ApplicationData.Current.LocalFolder;
// You are going to replace the file
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenStreamForWriteAsync())
{
var content = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
await stream.WriteAsync(content, 0, content.Length);
}
To quote the documentation :
ReplaceExisting : Create the new file or folder with the desired name,
and replaces any file or folder that already exists with that name.
I have clear the file by writing a empty string to it and then i have written what i wanted in my file This solved my issue as nothing was there in the file so whatever i wanted to write to it came up successfully.
Simply use Stream.SetLength like this:
using (var s = await file1.OpenStreamForWriteAsync())
{
// Add this line
s.SetLength(0);
// Then write new bytes. use 's.SetLength(fileBytes.Length)' if needed.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
s.Write(fileBytes, 0, fileBytes.Length);
}

How to create XML file to some folder?

How to create XML file to some folder?
isoStream = new IsolatedStorageFileStream("**Folder/XmlFile.xml**", FileMode.Create, isoStore);
Snatched directly from the Quickstart: Working with files and folders in Windows Phone 8
Check out the section "Creating a folder and writing to a text file"
private async void btnWrite_Click(object sender, RoutedEventArgs e)
{
await WriteToFile();
// Update UI.
this.btnWrite.IsEnabled = false;
this.btnRead.IsEnabled = true;
}
private async Task WriteToFile()
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(this.textBox1.Text.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.ReplaceExisting);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
Below function will save the Jagged array double[][] to the XML. You may use it by modify to your own data type:
private void Save(double[][] m, string filePath)
{
//Open a file stream
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
// Create a xml Serializer object
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(double[][]));
xmlSer.Serialize(fs, m);
// Close the file stream
fs.Close();
}
Just instead of the double [][] m you should put your own type.

Categories

Resources