Solved

System.UnauthorizedAccessException: Access to the path denied

Posted on 2009-04-10
4
8,493 Views
Last Modified: 2012-06-21
Hello,
I am having a strange System.UnauthorizedAccessException when trying to create a file.
I do have full permission to the directories in question. In this particular case, I am using the directory: C:\documents and settings\all users\Application Data\__DELETE_TEST for my unit test.

Note that CPath is class that hold the string path and has helper methods to do System.IO type operations. It can lazily load a FileInfo class as used in the code example.

The test assembly reference the assembly that contains the class Dp2ScriptBuilder.
In the test when I invoke,  dsb.SaveToPath( dpl.ScriptHistory.Combine( dsb.FileNameWithTimeStamp ) ), the file is save correctly.
However, when I invoke it fails with:
Dp2ScriptStatusTest.CanWriteInDP2FakeCommandDirectory : Failed281 [7] DEBUG Dp2ServiceTest (null) -
 ScriptHistory Path: C:\documents and settings\all users\Application Data\__DELETE_TEST\Commands\History
 ScriptError Path C:\documents and settings\all users\Application Data\__DELETE_TEST\Commands\Error
 ScriptQueuePath: C:\documents and settings\all users\Application Data\__DELETE_TEST\Commands

System.UnauthorizedAccessException: Access to the path 'C:\documents and settings\all users\Application Data\__DELETE_TEST\Commands\History' 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)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append)
at System.IO.FileInfo.CreateText()
at Org.Model.DP2.DP2ScriptBuilder.SaveToPath(CPath path) in DP2ScriptBuilder.cs: line 147
at Org.Model.DP2.DP2ScriptBuilder.InternalSaveToPath() in DP2ScriptBuilder.cs: line 158
at Dp2ServiceTest.Dp2ScriptStatusTest.CanWriteInDP2FakeCommandDirectory() in Dp2ScriptStatusTest.cs: line 57



The only difference between the call is that internalSavePath calls the SavePath. There may be an issue with code access security but i am not sure what?



public class DP2ScriptBuilder
    {
[...]   
public void SaveToPath(CPath path)
        {
            using (StreamWriter sw = path.FInfo.CreateText())
            {
                sw.Write(ToString());
                sw.Flush();
                sw.Close();
            }
 
        }
 
        public void InternalSaveToPath()
        {
            SaveToPath(_pathLocations.ScriptHistory);
 
        }
 
[...]
}
 
 
 [TestFixture]
    public class Dp2ScriptStatusTest : AbstractTestModule
    {
 
        const string IDENTITYNAME = "Dp2ScriptStatusTest"; 
[...]
 
  [Test]
        public void CanWriteInDP2FakeCommandDirectory()
        {
            DP2PathLocation dpl = GetFakePathLocation();
            int orderid = 9999;
 
            DP2ScriptBuilder dsb = DP2ScriptBuilder.GetScript(orderid, dpl, IDENTITYNAME)
                                                   .IncludeMacro();
 
            dsb.AddLine("Some test lines");
 
            logbase.DebugFormat("\n ScriptHistory Path: {0} \n ScriptError Path {1} \n ScriptQueuePath: {2}", dpl.ScriptHistory, dpl.ScriptError, dpl.ScriptQueue);
 
           // dsb.SaveToFile( dpl.ScriptHistory.Combine( dsb.FileNameWithTimeStamp ) );
            //var enqueueSuccess = dsb.EnQueueCommandScript("CanWriteInDP2CommandDirectorySaveToFile");
            dsb.SaveToPath( dpl.ScriptHistory.Combine( dsb.FileNameWithTimeStamp ) );
            dsb.InternalSaveToPath();
           
 
          // Expect(enqueueSuccess, Is.True);
           Expect(File.Exists(dpl.ScriptHistory.Combine(dsb.FileNameWithTimeStamp)));
           //Expect(File.Exists(dpl.ScriptQueue.Combine(dsb.FileNameWithTimeStamp)));
           //TODO: ensure file doesn't exists before, and at teardown delete created files
        }
 
        private DP2PathLocation GetFakePathLocation()
        {
            string dp2RootPath =  @"C:\documents and settings\all users\Application Data\__DELETE_TEST";
 
            return new DP2PathLocation(-1, dp2RootPath, String.Empty);
        }
 
[...]
}

Open in new window

0
Comment
Question by:collages
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 12

Expert Comment

by:williamcampbell
ID: 24116884
C:\documents and settings\all users\Application Data\__DELETE_TEST\Commands\History

Does this path exist? Maybe you have to create the folders first...
0
 
LVL 1

Author Comment

by:collages
ID: 24117005
The path exists and i verified it, if it didn't I would get not exist type error.
0
 
LVL 1

Accepted Solution

by:
collages earned 0 total points
ID: 24117081
I found out what the problem was. The internalSave was trying to create the file to the directory instead of specifying the filename.
So when attempting to save a file to a directory you get the error.

 public void InternalSaveToPath()
        {
            SaveToPath(_pathLocations.ScriptHistory);
 
        }
should be
 public void InternalSaveToPath()
        {
            SaveToPath(_pathLocations.ScriptHistory.Combine(FilenameWithStamp);
 
        }

Thanks

0
 
LVL 12

Expert Comment

by:williamcampbell
ID: 24117203
Did my question help you in your thought process which led to  the solution? If not then closing this is OK.
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question