繁体   English   中英

如何在Android上使用Xamarin.Forms创建文件?

[英]How to create a file with Xamarin.Forms on Android?

我想在我的android手机上创建一个公共文件,无需root访问权限即可找到它。 用户可以找到并阅读的地方。

我当前的代码在Visual Studio错误列表中没有给出错误。 关于无法读取带有调试符号的mono.android.dll之类的文件以及在FileSaver类中未使用声明的异常的警告只有36条。 目前,我认为这无关。 我没有例外。 我的代码成功发送到文件创建警报。

如果有人可以将我推向正确的方向,或者知道我在犯的错误,那么我无所不能。

我的代码:

XAML按钮部分

<Button x:Name="CreateFile" />

XAML.CS构造函数和单击部分

public MyPage ()
{
    InitializeComponent ();            
    CreateFile.Clicked += OnCreateFileClicked;
}

private async void OnCreateFileClicked(object sender, EventArgs e)
{
    IFileSaver FileSaver = DependencyService.Get<IFileSaver>();
    if (await FileSaver.CreateFile())
    {
        await this.DisplayAlert("The file is created","Created file","Okay","Okay");
    } else
    {
        await this.DisplayAlert("The file is NOT CREATED", "The file is NOT CREATED", ":(", ";-;");
    }
}

接口

using System.Threading.Tasks;

namespace PvApp
{
    /*
     * You can't use C# friends File, Directory, Streamwriter etc. (system.io) in the PCL (public class library).
     * So we do it in the platform specific libraries.
     */
    public interface IFileSaver
    {        
        Task<bool> CreateFile();
    }
}

FileSaver类

using System.Threading.Tasks;
using Xamarin.Forms;
using PvApp.Droid.Assets;

[assembly: Dependency(typeof(FileSaver))]

namespace PvApp.Droid.Assets
{ 
    class FileSaver : IFileSaver
    {
        public async Task<bool> CreateFile()
        {           
            //TRIED: .MyDocuments, 
            string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string path = System.IO.Path.Combine(folder, "test.txt");

            try 
            {
                System.IO.File.Create(path);
                return await Task.FromResult(true);
            } 
            catch (System.Exception exception)
            {
                return await Task.FromResult(false);
            }  
        }
    }
}

我做的事

1:

我看了Xamarin大学的这段视频,向我展示了我可以使用System.IO命名空间中的一些老朋友,例如File,Directory等( https://youtu.be/Xrh6ZJcxtZ8(4:14 ))。

视频还向我展示了只能在特定于平台的项目中访问它们( https://youtu.be/Xrh6ZJcxtZ8(4:35 ))。

因此,我在PCL库中创建了一个接口,并添加了一个类,该类在我的Android平台特定的项目资产文件夹中实现了该接口。 我输入了已有的代码(请参见上面的1:代码块)。 我在点击事件处理程序的页面中调用了该接口。 该代码运行良好,并且收到成功警报,但是我无法在设备上找到该文件。

2:

诸如此类的问题并不能解决我的问题:

如何在Xamarin中使用Android的内部存储? 如何在Android中创建文件?

3:

我检查了是否需要权限。 内部存储不需要权限。

4:

我尝试了来自网站或StackOverflow问题的其他代码,这些代码应该创建一个文件。 例如,Application.Context.FilesDir.Path并没有帮助。 我无法使其工作。 为了这篇文章的长度,我将它们排除在外。

尝试过Riciprinis代码:

{System.UnauthorizedAccessException: Access to the path "/test.txt" is denied.
 at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) [0x001b7] in <4d6eb5dfe2ab4eee884ef920069afd5f>:0 
 at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize) [0x00000] in <4d6eb5dfe2ab4eee884ef920069afd5f>:0 
 at (wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int)
 at System.IO.File.Create (System.String path, System.Int32 bufferSize) [0x00000] in <4d6eb5dfe2ab4eee884ef920069afd5f>:0 
 at System.IO.File.Create (System.String path) [0x00000] in <4d6eb5dfe2ab4eee884ef920069afd5f>:0 
 at PvApp.Droid.Assets.FileSaver+<CreateFile>d__0.MoveNext () [0x00058] in (Filepath to my FileSaver.cs and to function System.IO.File.Create(path);)

尝试过Riciprinis内部存储权限:

<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

Riciprini建议的断点

在此处输入图片说明 在此处输入图片说明

如果我在没有Riciprini的建议的情况下使用Path.Combine /

在此处输入图片说明

是什么解决了我的问题

我拒绝了Riciprinis的建议,所以我放弃了/并遵循Riciprinis的建议来更改文件夹字符串。

这段代码可以解决问题,甚至可以完成工作(请看我和Rciprini之间的对话,他的回答中有我所做的更多事情):

下面的代码位于我的FileSaver类的CreateFile函数中,原始文件夹和路径在此处。

string folder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;            
string path = System.IO.Path.Combine(folder, "test.txt");    

解:

string folder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;            

如果要添加请求运行时权限,请遵循此请求运行时权限

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM