System.UnauthorizedAccessException Access to the path is denied

yogesh lawate picture yogesh lawate · Aug 22, 2013 · Viewed 20.4k times · Source

At attempt to write PDF document with following code:

document = new Document();
PdfWriter writer = null; ;
try
{
    writer = PdfWriter.GetInstance(document, new FileStream(@"E:\mergFiles", FileMode.Create));
}
catch (Exception xc)
{ }

I am getting an exception:

{System.UnauthorizedAccessException: Access to the path 'E:\mergFiles' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode)
   at PDFLibrary.PDFManager.MergeDocs()}

I have all access to this folder.

goggled and found that this could help File.SetAttributes(@"E:\mergFiles", FileAttributes.Normal); but still I'm getting the same exception.

Answer

Thorsten Dittmar picture Thorsten Dittmar · Aug 22, 2013

Well, you can't pass the name of a folder to a FileStream. It needs to be a file name including the path (edit: of course it doesn't really have to include the path if you use a relative file name).

If you want to create a folder, use Directory.CreateDirectory. To create a file within that folder, use something like this:

string fullName = Path.Combine(pathName, fileName);
writer = PdfWriter.GetInstance(document, new FileStream(fullName, FileMode.Create));