Solved

System.UnauthorizedAccessException: Access to the path denied

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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

770 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