[IronPython] Converting IronPython file object to .NET Stream object

Dino Viehland dinov at microsoft.com
Tue Jan 4 19:01:23 CET 2011

Can wrote:
> Is there an easy way to convert an IronPython file-like object to a .NET
> Stream? The reverse can be done in IronPython using like this:
> net_stream = File.OpenRead('file.txt')
> python_file = file(net_stream)
> I wonder if there is an easy way of doing the reverse? Or do you have to
> write a wrapper that will inherit from Stream and implement all the
> methods?

The stream is not currently accessible - it also doesn't actually always exist because
when we're writing to the console we use a different object (I actually don't 
remember why this is - maybe we could wrap that object in a stream and always 
have a stream).

We could easily expose the Stream has a PythonHidden property (so it requires import 
clr) or add something like clr.FileToStream() to get the stream for normal files though.
Or given that we're all consenting adults you could use reflection to get the stream:

import System
f = file('abc.txt', 'w+')
f.GetType().GetField('_stream', System.Reflection.BindingFlags.Instance | 

More information about the Ironpython-users mailing list