Share via


System.IO.DirectoryNotFoundException: Could not find a part of the path

Question

Wednesday, February 15, 2012 2:59 AM

I have been getting this message.  sometimes the code just works fine, sometimes the error occurs.

Could not find a part of the path 'C:\User\Documents\ Sites\MySite\page\form.pdf'.

here is the code that creates the file and the error line

@using System.IO;
.....
@{
.....
try{
var output = new FileStream(Server.MapPath("form.pdf"),FileMode.Create);
            var writer = PdfWriter.GetInstance(doc, output);

......
catch (DocumentException dex)
            {
                throw (dex);
            }
            catch (IOException ioex)
            {
                throw (ioex); (the error is on this line)
            }
            finally
            {
                doc.Close();
            }

All replies (5)

Wednesday, February 15, 2012 2:58 PM ✅Answered

You would need to ensure that the directory is created prior to creating the file.

    var appDataPath = Server.MapPath("~/App_Data/");
    if (!Directory.Exists(appDataPath)) {
        Directory.Create(appDataPath);
    }
    var filePath = Path.Combine(appDataPath, Path.GetRandomFileName() + ".pdf");
    using (var output = File.Create(filePath)) {
       // Do stuff here

    }

Thursday, February 16, 2012 8:33 AM ✅Answered

That should be CreateDirectory:

 if (!Directory.Exists(appDataPath)) {
     Directory.CreateDirectory(appDataPath);
 } 

Wednesday, February 15, 2012 9:06 AM

Can you put the stack trace to know if the exception was thrown in the "new FileStream..." line or in the next one?


Thursday, February 16, 2012 7:38 AM

Thanks for the respose, i tried your code and the follwoing error occured.

**Compiler Error Message: **CS0117: 'System.IO.Directory' does not contain a definition for 'Create'

 if (!Directory.Exists(appDataPath)) {    

     Directory.Create(appDataPath); (error at this line)

    }

 

Crisfervil,

 from the first error; here is the

Stack Trace: 

[DirectoryNotFoundException: Could not find a part of the path 'C:\User\Documents\Sites\MySite\page\form.pdf'.]
   ASP._Page_Order_cshtml.Execute() in c:\User\Documents\Sites\MySite\page.cshtml:247
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
   System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors) +68
   System.Web.WebPages.WebPage.ExecutePageHierarchy() +156
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
   System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContext context) +249

Thursday, May 10, 2012 4:28 PM

You don't have to check, Directory.CreateDirectory() never throws an exception if the directory already exists.