UnifiedDirectory can not create a new directory

Per Selin
Member since: 2007



A have a function that shall create a new UnifiedDirectory and then save file in it but a only get

System.NullReferenceException: Objektreferensen har inte angetts till en instans av ett objekt

when directory bellow is equal with null or do not exist.

Have found some links like


That did help a lot but this last part will not work hmmmm...

UnifiedDirectory directory = HostingEnvironment.VirtualPathProvider.GetDirectory(path) as UnifiedDirectory;

if (directory != null)

file2 = directory.CreateFile(VirtualPathUtility.GetFileName(this.m_targetPath));

else //this do not work

UnifiedDirectory ud = UnifiedDirectory.CreateDirectory(path);

file2 = ud.CreateFile(VirtualPathUtility.GetFileName(this.m_targetPath));

#28352 Mar 04, 2009 17:28
  • Tore Gjerdrum
    Member since: 2006

    Hi Per.

    I usally use this approach:

    public static void SaveFile(string newpath, byte[] bytes)

    UnifiedDirectory dir;

    string virtualDir = VirtualPathUtility.GetDirectory(newpath);
    string virtualFile = VirtualPathUtility.GetFileName(newpath);

    if (HostingEnvironment.VirtualPathProvider.DirectoryExists(virtualDir))
    dir = VirtualPathHandler.Instance.GetDirectory(virtualDir, true) as UnifiedDirectory;

    dir = UnifiedDirectory.CreateDirectory(virtualDir);

    if (dir != null)
    dir.BypassAccessCheck = true;
    UnifiedFile newFile = dir.CreateFile(virtualFile);
    Stream newImage = newFile.Open(FileMode.Create, FileAccess.Write);
    newImage.Write(bytes, 0, bytes.Length);

    newpath is the path to the new file, while bytes is the an bytearray of the file to save.

    Hope this helps!

    BR, Tore

    #28353 Mar 04, 2009 17:53
  • Per Selin
    Member since: 2007

    Thanks for the help, you code send me in the rigth way

    It seems that it was the path sting that was causing some problem in my case


    #28371 Mar 05, 2009 14:48