Cannot implicitly convert type 'System.IO.Stream' to 'Java.IO.InputStream'

人走茶凉 提交于 2019-12-13 13:07:55

问题


I referred some similar questions on SO but none of them deals with IO.

I had used the same code in java when I used Eclipse. That time it worked.

But now I try to use this code in Mono for Android (C#), it doesn't work.

I'm trying to run this code to create an InputStream:

InputStream myInput =ctx.Assets.Open(DATABASE_NAME + ".db");

But it is giving me compile-time error : Cannot implicitly convert type 'System.IO.Stream' to 'Java.IO.InputStream'

There is a direct function to copy a file from assets to device memory but that requires source and destination path.

How do I get the source Path???

As I'm absolute beginner to Mono for Android, any help appreciated.


回答1:


Mono for Android translates some Java constructs into "equivalent" .NET constructs to ease code sharing between .NET-like platforms. As part of this, java.io.InputStream and java.io.OutputStream are mapped to System.IO.Stream, hence the compiler errors.

Is there anything you require that exists on InputStream that doesn't exist on System.IO.Stream?

There is a direct function to copy a file from assets to device memory but that requires source and destination path.

I have no idea what InputStream method you're referring to here. You can use Stream.CopyTo(Stream) to do that:

Stream asset = context.Assets.Open(DATABASE_NAME + ".db");
string dbPath = System.IO.Path.Combine(
        System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
        "YourFile.xml");
using (var dest = System.IO.File.OpenWrite(destPath))
    asset.CopyTo(dest);



回答2:


You are trying to convert System.IO.Stream to Java.IO.InputStream which is not allowed.. both are different environments.

What you want to achieve here can be done using System.IO.Stream, so no need to convert!!

            System.IO.Stream input = context.Assets.Open(FILENAME);
            Java.IO.FileOutputStream output = new Java.IO.FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int size;
            while ((size = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, size);
            }
            input.Close();
            output.Close();


来源:https://stackoverflow.com/questions/9906962/cannot-implicitly-convert-type-system-io-stream-to-java-io-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!