Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a Stream from a resource file / content

Is this the correct/only way of getting a Stream from a resource file?

    Uri uri = new Uri(fullPath);

    StorageFile storageFile = 
      await Windows.Storage.StorageFile.
        GetFileFromApplicationUriAsync(uri);

    IRandomAccessStreamWithContentType randomAccessStream = 
      await storageFile.OpenReadAsync();

    IInputStream resourceStream = (IInputStream)
      randomAccessStream.GetInputStreamAt(0);

All my other sources (http and local storage) return a Stream object, and it is painful to have to if-else code that uses one or the other.

I've also tried to just create a MemoryStream out of it, but I can't even find a way to get the bytes out... Please help.

    uint size = (uint)randomAccessStream.Size;
    IBuffer buffer = new Windows.Storage.Streams.Buffer(size);
    await randomAccessStream.ReadAsync(buffer, size, 
      InputStreamOptions.None);

    Stream stream = new MemoryStream(buffer); // error takes byte[] not IBuffer

IInputStream.ReadAsync() when reading from resource: http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.streams.iinputstream.readasync.aspx

while Stream.Read() and Stream.ReadAsync() look like this:

http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx

and

http://msdn.microsoft.com/en-us/library/hh137813.aspx

Thanks

like image 370
swinefeaster Avatar asked Dec 13 '12 09:12

swinefeaster


People also ask

How do I read a resource folder in Java 8?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().

How do I add a resource file to a jar file?

1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR!


2 Answers

Ok I found it!

    StorageFile storageFile =
      await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

    var randomAccessStream = await storageFile.OpenReadAsync();
    Stream stream = randomAccessStream.AsStreamForRead();
like image 83
swinefeaster Avatar answered Sep 22 '22 09:09

swinefeaster


You can also do it in one less line:

Stream stream = await storageFile.OpenStreamForReadAsync(); 
like image 40
ickydime Avatar answered Sep 23 '22 09:09

ickydime