Why am I getting a "Could not find a part of the path" exception?

Shashank picture Shashank · Sep 11, 2013 · Viewed 99.4k times · Source

I am developing website using Visual Studio 2010. I am trying to save a file in a path. It works fine localhost.

But the same code is not working in IIS. It shows the following error

Exception Details: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Inetpub\wwwroot\Vendor\cn.jpg'.

Could not find a part of the path 'C:\Users\shashank\Desktop\ab.csv'.

Here is the code:

protected void btnImportFile_Click(object sender, EventArgs e)
{
    sArReportText = File.ReadAllText(txtFilePath.Text.Trim());
    // Set the report Properties to insert Report information
    SetProperties();
}

Answer

bugmagnet picture bugmagnet · Aug 26, 2015

You might also be experiencing what I am: that the directory name contains some unusual characters. In my case,

Could not find a part of the path 'C:\Web\metBoot\wild iis\DigiCert© Certificate Utility for Windows_files'.

That copyright sign is the issue.

So using concepts drawn from Obtaining the short 8.3 filename from a long filename, I convert my paths to short form first, then use that to get my list of files.

StringBuilder sf = new StringBuilder(300);
int n = GetShortPathName(sourceFolder, sf, 300);
if (0 == n)
{
   tk.write(Marshal.GetLastWin32Error().ToString());
   continue;
}

...

 IEnumerable<string> fileGroup = Directory.EnumerateFiles(sf.ToString(), ext);