This project is read-only.

LoadXnb overloader

May 9, 2010 at 2:41 PM
Edited May 9, 2010 at 2:47 PM


I have been using Silversprite for a while now and I have added a little code to make it easier for myself to work with resource files from other assemblies.

For that I created an overloading method for LoadXnb(file, assemblyName);



public virtual T LoadXnb<T>(string assetName, string assembly)
            if (this.disposed)
                throw new ObjectDisposedException(base.ToString());   // Prints out the full type information as the message

            if (string.IsNullOrEmpty(assetName))
                throw new ArgumentNullException("assetName");       // We can't load an asset if we don't know it's name

            // Try to get a stream for the supplied asset
            Stream assetStream = GetResourceStream(assetName, ".xnb", assembly);

            // Get the graphics device from the service provider to pass to the contentreader
            GraphicsDevice graphicsDevice = ((IGraphicsDeviceService)this.serviceProvider.GetService(typeof(IGraphicsDeviceService))).GraphicsDevice;

            // Create a contentreader for the stream to read out the asset (whatever it is)
            ContentReader contentReader = new ContentReader(this, assetStream, graphicsDevice);

            // Get the asset's type readers. There can be a few of these like for the model class.
            ContentTypeReader[] assetReaders = GetAssetReaders<T>(contentReader);
            contentReader.TypeReaders = assetReaders;
            ContentTypeReaderManager manager = new ContentTypeReaderManager(contentReader);
            foreach (ContentTypeReader r in assetReaders)
            // billreiss need to read a byte here for things to work out, not sure why

            // Get the 1-based index of the typereader we should use to start decoding with
            int index = assetStream.ReadByte();
            T asset = contentReader.ReadObject<T>(assetReaders[index - 1]);

            return asset;

 private Stream GetResourceStream(string assetName, string extension, string assembly)
            Stream stream = null;
            string path = Path.Combine(this.rootDirectory, assetName + extension);
            path = path.Replace("\\", "/");
            path = string.Format("/{0};component/{1}", assembly, path);
			StreamResourceInfo info = Application.GetResourceStream(new Uri(path, UriKind.Relative));
			if (info == null) return null;
			stream = info.Stream;
            return stream;


It's just a sloppy duplicate but I'd be very happy if you integrate this into your souce code somehow :)


Thanks in advance!