System.UnauthorizedAccessException accessing file

M

Mike Hofer

Hi folks,

In my Windows Forms application, the following exception is thrown when
I attempt to delete or access a specific file:

System.UnauthorizedAccessException: Access to the path 'C:\Documents
and Settings\hofer\My Documents\Visual Studio
Projects\CiviGenics.Roswell\bin\Roswell Settings.xml' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String
maybeFullPath)
at System.IO.File.Delete(String path)
at Civigenics.Roswell.Settings.SaveSettings() in C:\Documents and
Settings\hofer\My Documents\Visual Studio
Projects\CiviGenics.Roswell\Classes\General\Settings.vb:line 324

The code in question follows:

<PermissionSet(SecurityAction.LinkDemand, name:="FullTrust")> _
Private Shared Sub SaveSettings()

Dim tw As XmlTextWriter
Dim filePath As String
Dim xml As String

Try

If m_settingsFile IsNot Nothing Then
xml = m_settingsFile.InnerXml
m_settingsFile = Nothing
End If

filePath = GetSettingsFileName()
If File.Exists(filePath) Then
File.Delete(filePath)
End If

tw = New XmlTextWriter(filePath, Nothing)
m_settingsFile = New XmlDocument()
m_settingsFile.InnerText = xml
m_settingsFile.WriteTo(tw)

Catch ex As Exception
Debug.WriteLine(ex.ToString())
Stop

Finally
If tw IsNot Nothing Then
tw.Flush()
tw.Close()
End If
End Try

' Setting m_settingsFile to Nothing forces a reload on the
next access.
m_settingsFile = Nothing

End Sub

It breaks on the line, File.Delete(filePath). The application is trying
to work with an .XML located file in my application's folder. For some
reason, any time I try to delete or write to it,
UnauthorizedAccessException is thrown. The file is not marked
read-only. The application is running as me, and I have administrative
privileges on the machine.

I need to be able to rewrite this file whenever the user modifies my
application's settings via the Options dialog. (The data I want to
store is not easily stored in My.Settings -- it's heirarchical in
nature.)

Thanks in advance,
Mike
 
M

Mike Hofer

Found the problem, I think.

I had set the XML file up to be copied automatically into the
application folder upon build. While the file wasn't being marked
read-only, it appears that the build process was holding a lock on the
file, for some reason. I had to get rid of the old file, remove the
"Copy if newer" setting, clean the solution, and rebuild.

Everything worked like a charm.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top