加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何从xamarin中的绝对NSURL加载文件

发布时间:2020-12-15 23:32:07 所属栏目:百科 来源:网络整理
导读:我正在使用Xamarin为 IOS开发一个应用程序,使用opengl游戏模板作为开始. 我已经设置了我的应用程序,以便能够打开某种文件格式,并在AppDelegate.cs中覆盖了OpenURL委托 问题是如果我这样做: public override bool OpenUrl(UIApplication application,NSUrl u
我正在使用Xamarin为 IOS开发一个应用程序,使用opengl游戏模板作为开始.

我已经设置了我的应用程序,以便能够打开某种文件格式,并在AppDelegate.cs中覆盖了OpenURL委托

问题是如果我这样做:

public override bool OpenUrl(UIApplication application,NSUrl url,string sourceApplication,NSObject annotation)
        {

            Stream bob = new FileStream(url.AbsoluteString,FileMode.Open,FileAccess.Read);
            return true;
        }

我得到一个例外的东西

"Unable to open file : /private/var/mobile/Applications/A7B5E435-F7D1-4985-BA97-C243E63EFC39/MyApp.app/file:///private/var/mobile/Applications/A7B5E435-F7D1-4985-BA97-C243E63EFC39/Documents/Inbox/A%20File%20To%20Open.ext"

这似乎是因为url.AbsoluteString返回文件:/// … part但是FileStream总是想要一个更加清理的路径(例如s替换为空格)相对于必须是app的bundle dir

/private/var/mobile/Applications/A7B5E435-F7D1-4985-BA97-C243E63EFC39/MyApp.app/

最后,我得到它以非常黑客的方式获取url.AbsoluteString,删除“file:///”部分,添加一堆../../../等到开头,和用“”代替“”.

public override bool OpenUrl(UIApplication application,NSObject annotation)
        {
            string fname = "../../../../../../../../../" + (url.AbsoluteString).Replace("%20"," ").Replace("file:///","");
            Stream bob = new FileStream(fname,FileAccess.Read);
            return true;
        }

这有效……但它看起来非常糟糕.那么使用Xamarin从NSURL获取可读文件流的正确方法是什么?

(注意这是在IOS 7上,在IOS 9中,传入的路径在很多方面与FileStream的默认目录不同,在dir树中也是高级别的)

解决方法

使用NSUrl类上的Path属性:

NSString urlString = new NSString("file:///stack/over%20flow/foobar.txt");
NSUrl myFileUrl = new NSUrl (urlString);
Console.WriteLine (myFileUrl.AbsoluteString);
string absPath = myFileUrl.Path;
Console.WriteLine (absPath);

2016-04-12 18:38:53.809 filepath[11174:1132929] file:///stack/over%20flow/foobar.txt
2016-04-12 18:38:53.814 filepath[11174:1132929] /stack/over flow/foobar.txt

参考:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/index.html#//apple_ref/occ/instp/NSURL/path

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读