?
Solved

System.UnauthorizedAccessException: Access to the path denied

Posted on 2009-04-10
4
Medium Priority
?
8,555 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
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…
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.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month10 days, 14 hours left to enroll

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