Skip to main content
 首页 » 编程设计

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

2024年02月13日12thcjp

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

    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 并且由于这个原因,如果要写入文件的新信息与 privous 相比在长度方面更短length 然后在新文件结束后出现一些垃圾值或不必要的东西

请您参考如下方法:

您可以使用此代码段:

var folder = ApplicationData.Current.LocalFolder; 
// You are going to replace the file 
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); 
using (var stream = await file.OpenStreamForWriteAsync()) 
{ 
    var content = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total)); 
    await stream.WriteAsync(content, 0, content.Length); 
} 

引用documentation :

ReplaceExisting : Create the new file or folder with the desired name, and replaces any file or folder that already exists with that name.