Search code examples
c#exceptionadministrator

Exception: Access Denied when using FileStream


The following line is throwing an exception. I have no idea why.

using (var output = new FileStream(sftpFile.Name, FileMode.Create,FileAccess.ReadWrite))

Exception is:

Error: System.UnauthorizedAccessException: Access to the path 'C:\Users\roberth\
Programming_Projects\Common\UI\bin\Debug' 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, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at CWD.Networking.DownloadFromSftp(String hostname, String user, String passw
ord, Int32 port, String localPath, String remotePath, String filename) in c:\Use
rs\roberth\Programming_Projects\Common\Common\Common.cs:line 566

Line 566 is the using statement above.

Can anyone shed some light as to why I may be triggering an error? I have full permissions to the directory, no compilation issues, I can create new files and folders manually in that directory as well.

--Edit--

I tried running VS as administrator as suggested with no resolution.


Solution

  • The UnauthorizedAccessException error message tells you what file it is you're trying to open:

    C:\Users\roberth\Programming_Projects\Common\UI\bin\Debug
    

    This looks like a directory name: you can't open a directory as a file.

    You've presumably forgotten to append a filename:

    string filename = Path.Combine(sftpFile.Name, "SomeFile.dat");
    using (var output = new FileStream(filename,...)
    {
        ...
    }