about C#, C++, Java, sql, java script etc.

Tuesday, January 26, 2010

Writing/reading a protected file in asp.net

Some of you may run into the error "Access to the path '...' is denied" while creating a protected file in asp.net. Well, one should first check if the user account used to execute asp.code has enough rights to access a folder you try to save the file in. As long as one doesn't use impersonation this user is either NETWORK SERVICE or ASPNET.
I created a new user account for the asp.net impersonation, added necessary rights to the protected folder but was still receiving the same "Access denied" exception. Adding the permission "Log on as a batch job" for the user account solved the problem. It seems that Windows uses the batch-queue to perform I/O operations while accessing encrypted files. This only holds if files are accessed under asp.net. Win-Forms applications don't require this permission to access encrypted files.

*Steps* to solve the problem:
  1. Open Control Panel
  2. Administrative Tools -> Local Security Settings -> User Rights Assignments
  3. Find the policy Log on as a batch
  4. Add your user account/group into it

Sunday, January 24, 2010

Convert relative path to absolute in VB.NET

Recently I've found a good way to get an absolute path out of a base and relative paths. Before I used the method Directory.SetCurrentDirectory(). But changing the current directory to a base directory, then to one in a relative path and finally reading the resulting path with Directory.GetCurrentDirectory() is kind of clumsy.
.NET provides a better solution in the class Uri:

 ''' <summary>
 ''' Constructs and returns an absolute path if <paramref name="absoluteOrRelativePath"/> is a relative path.
 ''' Otherwise <paramref name="absoluteOrRelativePath"/> is returned.
 ''' </summary>
 ''' <param name="basePath"></param>
 ''' <param name="absoluteOrRelativePath"></param>
 ''' <returns></returns>
 Function GetAbsolutePath(ByVal basePath As String, ByVal absoluteOrRelativePath As String) As String
   Dim baseUri As Uri = New Uri(basePath)
   Dim resultUri As Uri = baseUri

   Uri.TryCreate(baseUri, absoluteOrRelativePath, resultUri)

   Return resultUri.AbsolutePath
 End Function 

Examples:
GetAbsolutePath("c:\temp\", "cache/") c:/temp/cache/
GetAbsolutePath("c:\windows\app.conf", "system32/") c:/windows/system32/
GetAbsolutePath("c:\windows\temp\", "d:\cache\") d:/cache/