Search code examples
c#raspberry-pi3createfilewindows-iot-core-10create-directory

Windows IoT Raspberry Pi 3 c# Check Folder Exist Create if not


I am trying to check if a folder exist .. if it doesn't i will need to create a folder. My code seems to work if the folder does not exist and create a folder... but subsequently after create the folder.. it runs into exception handler.. I am not sure where went wrong.. please advise. Thanks.

        StorageFolder externalDevices = KnownFolders.RemovableDevices;
        IReadOnlyList<StorageFolder> externalDrives = await externalDevices.GetFoldersAsync();
        StorageFolder usbStorage = externalDrives[0];
        String folderName = "Recordings";
        String fileName = DateTime.Now.ToString();

        if (!Directory.Exists(folderName))
        {
            await usbStorage.CreateFolderAsync(folderName);
        }

        await usbStorage.GetFolderAsync(folderName);
        StorageFolder recordFolder = await usbStorage.GetFolderAsync(folderName);
        StorageFile recordFile = await recordFolder.CreateFileAsync("Recording -" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".mp3", Windows.Storage.CreationCollisionOption.GenerateUniqueName);

        RecordStatus.Text = "File setup OK ... ";

Solution

  • Firstly, using Directory.Exists to check whether a fold exist is not suitable here. The path parameter of Directory.Exists method is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. But in your code, the folderName is not relative to your working directory(in fact,your working directory is Windows.ApplicationModel.Package.Current.InstalledLocation).

    Secondly, in UWP, the method of CreateFolderAsync has an overload method with CreationCollisionOption parameter.

    Please change this part in your code

    if (!Directory.Exists(folderName))
    {
         await usbStorage.CreateFolderAsync(folderName);
    }
    

    To

      await usbStorage.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
    

    It will be ok.