Search code examples
uwpwindows-10-iot-core

Creating a physical file with UWP on Windows IoT 10 Core


I tried to create some physical file in the device OS with Windows IoT 10 Core, using follow code:

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

I don't get any exceptions, however, when I search for the file using:

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

I don't find it.

In addition, storageFolder.Attributes equals FileAttributes.Archive.

If I use:

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

I get this exception:

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

This is configuration of 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>

How I can create a physical file to write log info to and read it further?


Solution

  • Your code is correct.

    You can use file.Path to get the file path. When you deploy UWP applicaton via Visual Studio it use DefaultAccount user. So the file path is C:\Data\Users\DefaultAccount\Pictures\robodem.log.

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

    And use -File instead of -Directory and remove the -ErrorAction SilentlyContinue. So try this command: Get-Childitem -Path c:\ -Include robodem.log -file -Recurse

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

    Not all folders on your device are accesible by Universal Windows Apps. Please refer to File access permissions.