Solved

System.UnauthorizedAccessException: Access to the path denied

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
I need C# converted to VB.net 1 53
C# Reverse int in fast ways 6 29
Hide Tab Page 3 20
Birthdays 3 22
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…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video discusses moving either the default database or any database to a new volume.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

743 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

10 Experts available now in Live!

Get 1:1 Help Now