Search code examples
c#asp.net-coresystem.io.file

I am getting this error in the following lines of code DirectoryNotFoundException: Could not find a part of the path


Here I am getting an error from the using line

using (var filestream = new FileStream(fullPath, FileMode.Create))
{
    await file.CopyToAsync(filestream).ConfigureAwait(false);
}
names.Add(name);

Here, I am getting an error in the if block.

if (files.Any())
{
    var names = await FileTransactionManager.SaveFileAsync(files, path2);
    var ancients = JsonConvert.DeserializeObject<string[]>(getEntity.NAME);
    names.AddRange(ancients);
    getEntity.NAME = JsonConvert.SerializeObject(names.ToArray());
}

If I need to explain the problem in general, I get an error when trying to add files in the program. The reason for the error is in the lines of code I have described.

That's the whole error message DirectoryNotFoundException: Could not find a part of the path 'C:\Users\muhasebe\Documents\GitHub\BO_Sleader2\CoreFramework.SLeader\wwwroot\klasorler\Fiyat_Listeleri\294_Haftalik_Rapor14.pdf'.

Does anyone have an idea why I am getting this error through these codes?


Solution

  • Check if the directory exist: "C:\Users\muhasebe\Documents\GitHub\BO_Sleader2\CoreFramework.SLeader\wwwroot\klasorler\Fiyat_Listeleri" create it if not!

    string path = @"C:\Users\muhasebe\Documents\GitHub\BO_Sleader2\CoreFramework.SLeader\wwwroot\klasorler\Fiyat_Listeleri\";
    
    // or 
    // string path = Path.Combine(_hostingEnvironment.WebRootPath, "klasorler\Fiyat_Listeleri")
    
    if (!Directory.Exists(path))
    {
       Directory.CreateDirectory(path);
    }