Solved

System.UnauthorizedAccessException: Access to the path denied

Posted on 2009-04-10
4
8,347 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
  • 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

895 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now