我正在制作一个应用程序,其中我要覆盖我的文件,就像我在文件中写一个数字并阅读但下次我想将新数字添加到现有文件然后阅读它
用于写入我正在使用代码的文件
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);
}
}
并用于阅读文件
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");
}
}
帮我看看如何在windows phone app开发中覆盖现有文件。
提前致谢
答案 0 :(得分:1)
据我了解,您不需要覆盖,但可以附加。
1)将ReplaceExisting
更改为OpenIfExists
:
var file = await dataFolder.CreateFileAsync("MyFile.txt", CreationCollisionOption.OpenIfExists );
2)在写之前寻找流的末尾:
using (var s = await file.OpenStreamForWriteAsync())
{
s.Seek(0, SeekOrigin.End );
s.Write(fileBytes, 0, fileBytes.Length);
}