如何在写入文件之前清除文件

时间:2014-02-28 14:25:32

标签: c# windows-phone-7 windows-phone-8

我正在使用此代码写入我的文件:

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

        }
    }

但在写入之前,我希望我的文件应该被清除。我该怎么办?

这是我到目前为止所尝试过的,但问题是它将文件写入filebytes.length,并且由于这一点,如果要在文件中写入的新信息在长度方面与较少的信息相比较少然后在新文件结束后出现一些垃圾值或不必要的东西

3 个答案:

答案 0 :(得分:3)

您可以使用此代码段:

StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file1 = await folder.CreateFileAsync(fileName, 
CreationCollisionOption.ReplaceExisting); // You are going to replace the file
using (Stream s = await file1.OpenStreamForWriteAsync())
{
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
    await s.WriteAsync(fileBytes, 0, fileBytes.Length);
}

引用documentation

  

ReplaceExisting:创建具有所需名称的新文件或文件夹,   并用该名称替换已存在的任何文件或文件夹。

答案 1 :(得分:1)

我已经通过写一个空字符串来清除文件,然后我已经在我的文件中写了我想要的内容这解决了我的问题,因为文件中没有任何东西,所以无论我想写什么,它都成功了。< / p>

答案 2 :(得分:0)

只需使用Stream.SetLength,就像这样:

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