保存文件Windows Iot核心jpg格式时出错

时间:2016-08-12 19:44:16

标签: c# uwp iot windows-10-iot-core

我接下来编写了一个代码:      private async void WriteData()             {                 var removableDevices = KnownFolders.RemovableDevices;                 var externalDrives = await removableDevices.GetFoldersAsync();                 var drive0 = externalDrives [0];

            var testFolder = await drive0.CreateFolderAsync("test");
            var testFile = await testFolder.CreateFileAsync("test.jpg");

            var byteArray = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
            using (var sourceStream = new MemoryStream(byteArray).AsRandomAccessStream())
            {
                using (var destinationStream = (await testFile.OpenAsync(FileAccessMode.ReadWrite)).GetOutputStreamAt(0))
                {
                    await RandomAccessStream.CopyAndCloseAsync(sourceStream, destinationStream);
                }

            }

        }

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

            this.WriteData();


        }

        this.OnPropertyChanged(nameof(LastUpdatedDisplay));

    }

我的代码冻结了,我想知道如何保存该档案中的湿度和温度值, 这是保存此应用程序的最佳方式吗?

有人能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

因为在您第一次运行代码后,已经创建了“test”文件夹和“test.jpg”,所以当您再次运行代码时,您可能会收到此异常。你可以试试这个:

var testFolder = await drive0.GetFolderAsync("test");
var testFile = await testFolder.GetFileAsync("test.jpg");

而不是

var testFolder = await drive0.CreateFolderAsync("test");
var testFile = await testFolder.CreateFileAsync("test.jpg");

注意:这里我将test.jpg保存在外部SD卡上。如果您的设备中没有SD卡,则代码也会遇到此异常。

答案 1 :(得分:0)

在课堂上尝试此操作,MyClass是容器类的名称

StorageFolder testFolder;
public MyClass()
{
    var removableDevices = KnownFolders.RemovableDevices; 
    var externalDrives = await removableDevices.GetFoldersAsync(); 
    var drive0 = externalDrives[0];
    testFolder = await drive0.CreateFolderAsync("test");
    await testFolder.CreateFileAsync("test.jpg");
}

而且,在您的WriteData方法中,您只说

var testFile = await testFolder.GetFolderAsync("test.jpg");

<强>观察

  • WriteDataremovableDevices.GetFoldersAsync()
  • 时变慢
  • 当您使用计时器时,您需要尽可能快地保持Tick事件并尽可能节省资源