在 Windows IoT 10 Core 上使用 UWP 创建物理文件

Creating a physical file with UWP on Windows IoT 10 Core

我尝试使用以下代码在 OS 设备中使用 Windows IoT 10 Core 创建一些物理文件:

StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

try
{
    StorageFile file = await storageFolder.CreateFileAsync("robodem.log", CreationCollisionOption.ReplaceExisting);

    using (Stream fileStream = await file.OpenStreamForWriteAsync())
    using (var streamWriter = new StreamWriter(fileStream))
    {
        streamWriter.Write("test");
    }

    onMessageOccured(Severity.Success, "Done");
}
catch (Exception ex)
{
    onMessageOccured(Severity.Error, ex.Message);
}

但是,当我使用以下方法搜索文件时,我没有遇到任何异常:

Get-Childitem –Path c:\ -Include robodem.log -Directory -Recurse -ErrorAction SilentlyContinue

我没找到。

此外,storageFolder.Attributes 等于 FileAttributes.Archive

如果我使用:

StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

try
{
    using(FileStream stream = new FileStream("c:\robodem.log", FileMode.OpenOrCreate))
    using (StreamWriter streamWriter = new StreamWriter(stream))
    {
        streamWriter.Write("test");
    }

    onMessageOccured(Severity.Success, "Done Base");
}
catch (Exception ex)
{
    onMessageOccured(Severity.Error, ex.Message);
}

我得到这个异常:

Access to the path 'c:\robodem.log' is denied.

这是Package.appxmanifest的配置:

<Capabilities>
    <Capability Name="internetClient" />
    <uap:Capability Name="musicLibrary" />
    <uap:Capability Name="removableStorage" />
    <uap:Capability Name="picturesLibrary" />
    <uap:Capability Name="videosLibrary" />
    <uap:Capability Name="documentsLibrary" />
    <DeviceCapability Name="webcam" />
    <DeviceCapability Name="serialcommunication">
      <Device Id="any">
        <Function Type="name:serialPort" />
      </Device>
    </DeviceCapability>
</Capabilities>

我如何创建一个物理文件来写入日志信息并进一步读取它?

您的代码是正确的。

您可以使用file.Path获取文件路径。当您通过 Visual Studio 部署 UWP 应用程序时,它使用 DefaultAccount 用户。所以文件路径是C:\Data\Users\DefaultAccount\Pictures\robodem.log.

System.Diagnostics.Debug.WriteLine(file.Path);

并使用 -File 代替 -Directory 并删除 -ErrorAction SilentlyContinue。所以试试这个命令:Get-Childitem -Path c:\ -Include robodem.log -file -Recurse

Access to the path 'c:\robodem.log' is denied.

通用 Windows 应用程序无法访问您设备上的所有文件夹。请参考File access permissions.