在 Iot Core(通用应用程序)上保存文件时出错

Error Saving file on Iot Core (Universal App)

我正在尝试将数据保存在我的 Iot Core 上的 txt 文件中 (Windows 10), 在温度方面,我想将这些信息保存在 txt 中,例如:

   private async void _timer_Tick(object sender, object e)
    {
        DhtReading reading = new DhtReading();
        int val = this.TotalAttempts;
        this.TotalAttempts++;

        reading = await _dht.GetReadingAsync().AsTask();

        _retryCount.Add(reading.RetryCount);
        this.OnPropertyChanged(nameof(AverageRetriesDisplay));
        this.OnPropertyChanged(nameof(TotalAttempts));
        this.OnPropertyChanged(nameof(PercentSuccess));

        if (reading.IsValid)
        {
            this.TotalSuccess++;
            this.Temperature = Convert.ToSingle(reading.Temperature);
            this.Humidity = Convert.ToSingle(reading.Humidity);
            this.LastUpdated = DateTimeOffset.Now;
            this.OnPropertyChanged(nameof(SuccessRate));

            //Inserir aqui o método de gravação de arquivo.

                StreamWriter SW;
                SW = File.AppendText(@"Arquivo.txt");
                SW.WriteLine("Evento Gerado em: " + DateTime.Now.ToString() + Humidity + Temperature + "\n\r");
        SW.Close();
    }
}

这是向我显示的错误,有人知道吗?

"CS1061 'StreamWriter' does not contain a definition for 'Close' and no extension method 'Close' accepting a first argument of type 'StreamWriter' could be found (are you missing a using directive or an assembly reference?"

StreamWriter.Close() 在 UWP 中不存在,它仅在旧版 .NET 框架中可用。

并且不,您不需要在您的 UWP 项目中调用它,只需调用 Dispose() 方法就可以了。以下是您可以遵循的代码示例,

        using (var SW = File.AppendText(@"Arquivo.txt"))
        {
            SW.WriteLine("Evento Gerado em: " + DateTime.Now.ToString() + Humidity + Temperature + "\n\r");
        }

using 子句在超出范围时会自动调用 Dispose 方法。

实际上,如果您查看 .NET code,第 231 行,调用 Close() 等同于 Dispose(),只是它告诉 CLR 不要调用对象的终结器。

我想您可以在 UWP 应用中使用上面的代码片段。

顺便说一句,如果你想保存到外部存储上的txt文件,你需要在项目清单文件中显式声明该功能,在"Declarations"选项卡中,添加"File Type Associations",以及一个扩展名为 "txt" 的方案。它也适用于其他文件格式。