简体   繁体   English

写入文件前如何清除文件

[英]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 这是我到目前为止尝试过的,但是问题是它会将文件写入到filebytes.length,并且由于如果要写入文件的新信息在长度方面比私有长度少,则有些新文件结束后出现垃圾值或不必要的东西

You can use this snippet : 您可以使用以下代码段:

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

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. ReplaceExisting:使用所需名称创建新文件或文件夹,并用该名称替换任何现有文件或文件夹。

我通过向其中写入一个空字符串来清除文件,然后在文件中写入了我想要的内容。这解决了我的问题,因为文件中没有任何内容,因此我想要写入的所有内容均成功完成。

Simply use Stream.SetLength like this: 像这样简单地使用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM