覆盖在WP8现有的文件(Overwriting the existing file in wp8)

2019-10-19 09:35发布

我想提出的,我想我的覆盖文件的应用程序,像我在文件中写一些和阅读,但下一次我希望将新号码添加到现有的文件,然后读取它

写入到文件中,我使用的代码

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的应用开发一个现有的文件。

提前致谢

Answer 1:

据我所知,你不需要重写,但附加。

1)变化ReplaceExistingOpenIfExists

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


文章来源: Overwriting the existing file in wp8