i am making an app in which i want to overwrite my file , like i am writing a number in the file and reading but the next time i want to add the new number to the existing file then read it
for writing into the file i am using the code
private async void cross_Click(object sender, RoutedEventArgs e)
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(this.ScoreTB.Text.ToCharArray());
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var dataFolder = await local.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists);
var file = await dataFolder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
and for reading the file
private async void aboutus_Click(object sender, RoutedEventArgs e)
{
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
// Get the DataFolder folder.
var dataFolder = await local.GetFolderAsync("MyFolder");
// Get the file.
var file = await dataFolder.OpenStreamForReadAsync("MyFile.txt");
// Read the data.
using (StreamReader streamReader = new StreamReader(file))
{
this.Score.Text = streamReader.ReadToEnd();
}
}
else
{
MessageBox.Show("No File Created");
}
}
just help me how to overwrite a existing file in windows phone app development.
Thanks in advance
As I understand, you don't need an overwrite, but append.
1) change ReplaceExisting
to OpenIfExists
:
var file = await dataFolder.CreateFileAsync("MyFile.txt", CreationCollisionOption.OpenIfExists );
2) seek to the end of the stream before write:
using (var s = await file.OpenStreamForWriteAsync())
{
s.Seek(0, SeekOrigin.End );
s.Write(fileBytes, 0, fileBytes.Length);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.