Home > Back-end >  Creating hierarchy of folders
Creating hierarchy of folders

Time:09-27

So I am converting an mp3 into wav, using NAudio

Example

string InputAudioFilePath = @"C:\Users\sdkca\Desktop\song.mp3";
string OutputAudioFilePath = @"C:\Users\sdkca\Desktop\song_converted.wav";

using (Mp3FileReader reader = new Mp3FileReader(InputAudioFilePath, wf => new Mp3FrameDecompressor(wf)))
{
    WaveFileWriter.CreateWaveFile(OutputAudioFilePath, reader);
}

So in my view model, I am doing the following

  1. I am getting the Documents folder
private static readonly string DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  1. Then I am doing this
const string ext = ".wav";

var dlg = new OpenFileDialog
              {
                  Filter = Constants.FILEFILTER
              };

var res = dlg.ShowDialog();

if (res! == true)
{
    var AudioName = Path.GetFileNameWithoutExtension(dlg.FileName);
    var FoderParent = Path.Combine(DocumentsPath, Constants.TRANSCRIPTIONS);
    var ParentSubFolder = Path.Combine(FoderParent, Constants.AUDIO);
    var filename = Path.Combine(ParentSubFolder, $"{AudioName}{ext}");

    using var mp3 = new Mp3FileReader(dlg.FileName);
    using var ws = WaveFormatConversionStream.CreatePcmStream(mp3);
    WaveFileWriter.CreateWaveFile(filename, ws);
}

I am getting this error

System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\egome\OneDrive - Universidad Politécnica de Madrid\Documents\Transcriptions\Audio\10.wav'.'

What I do not understand is, that I am doing a combine between my folder and a new fileName.wav, that is required by the method

CodePudding user response:

Add this check before creating filename string

if(!Directory.Exists(ParentSubFolder))
    Directory.CreateDirectory(ParentSubFolder);
var filename = Path.Combine(ParentSubFolder, $"{AudioName}{ext}");

This way, you make sure all path parts exist.

  • Related