Windows phone 8 append line to file - c#

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");

Related

read text file from Azure FileShare in a method

I want to read the contents of a csv file that I have in my FileShare on my storageaccount in Azure, using Azure.Storage.Files.Shares library.
I am able to connect to the file using the ShareFileClient, but how can I then read the contents and process them (append a new line), in my code?
ShareFileClient file = ConnectToFile();
Steam content = await file.OpenReadAsync(true);
// gives a Stream object, that I cannot get to work to get the content.
What are the next steps to stream the contents of this file? I'm stuck at trying to get the read action to work with something like
using (Steam stream = new Stream() )
{
// The actions to read the stream go here
}
Any suggestions on how this could be achieved?
Regarding the issue, please refer to the following code
// read
using (var stream = await file.OpenReadAsync().ConfigureAwait(false))
using (var reader = new StreamReader(stream)) {
// read csv file one line by line
while (!reader.EndOfStream) {
var line =await reader.ReadLineAsync().ConfigureAwait(false);
Console.WriteLine(line);
}
}
//write
ShareFileProperties properties = await file.GetPropertiesAsync().ConfigureAwait(false);
var myPosition = properties.ContentLength;
var newData = "42,11,58, \"N\",85,12,45, \"W\", \"Worcester\", ND"+Environment.NewLine;
var bytes = Encoding.UTF8.GetBytes(newData);
await file.SetHttpHeadersAsync(myPosition + bytes.Length);
using (var writer = await file.OpenWriteAsync(overwrite: false, position:(myPosition -1)).ConfigureAwait(false)) {
await writer.WriteAsync(bytes, 0, bytes.Length);
await writer.FlushAsync();
}

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.

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);
}

Read files in WP8

i have a problem with reading file in WP8.
string text;
IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
IStorageFile storageFile = await applicationFolder.GetFileAsync("MyFile.txt");
IRandomAccessStream accessStream = await storageFile.OpenReadAsync();
using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
{
byte[] content = new byte[stream.Length];
await stream.ReadAsync(content, 0, (int)stream.Length);
text = Encoding.UTF8.GetString(content, 0, content.Length);
}
return text;
Sometimes the storagefile or the accessStream crash without a reason.
If I debug them, it works.
I have no idea why. Can anyone help me?
I'm using this piece of code. The result will be the texts within your txt file, shortened into a string, so let's say your txt file contains this.
This
is
a test.
Result will be
This\nis\na\test.
Then, all you need to do is to split them up.
string result = null;
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("services.txt"))
{
using (var stream = new IsolatedStorageFileStream("services.txt", FileMode.Open, store))
{
using (var fileReader = new StreamReader(stream))
{
result = fileReader.ReadToEnd();
}
}
}
This is how i split the message.
string[] tmp = result.Split(new char[] { '\r', '\n', '.' });
foreach (string str in tmp)
{
System.Diagnostics.Debug.WriteLine(str);
}
Hope this helps.

How to append a file, asynchronously in Windows Phone 8

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

Categories

Resources