public Texture2D Texture2DFromFile(string fileName)
{
Texture2D texture;
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
texture = Texture2D.FromStream(GraphicsDevice, stream);
stream.Flush();
stream.Close();
return texture;
}
Above is the code that I wrote to get around the missing FromFile method in the Texture2D class. It's just a simple method that opens a file into a FileStream, which is basically just a section of memory to use for reading and writing to files, it then sets the texture object to the data collected in the FromStream method, then flushes the stream to clear it all out, and then closes the stream which basically just closes the file and stops using it. There are a few arguments in the FromStream method call, but they're pretty simple to understand. We just use them to let the compiler know that we're going to open a file with the FileMode.Open argument, and read data from that stream with the FileAccess.Read argument. This also limits the current file to being read only while it is being used. The FileShare argument is an argument that allows the file to be opened in another place in the code before it is closed here. We add ".Read" after the FileShare to ensure that the file, if accessed anywhere else before this closes, is read only and cannot be overwritten.
EDIT: Forgot to mention how to use it. All you have to do is add this method to the Form1.cs class and call this method just like you would the Texture2D.FromFile in the code that Nick gives. You just remove the period from the line of code and it will call this method and do exactly the same thing as the FromFile method used to.
This post has been edited by Kilorn: 04 October 2012 - 10:38 AM

New Topic/Question
Reply






MultiQuote


|