Xamarin形式:如何在设备外部存储中创建文件夹和文件? [英] Xamarin forms: How to create folder and a file in device external storage?

查看:371
本文介绍了Xamarin形式:如何在设备外部存储中创建文件夹和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在设备的外部存储设备上的该文件夹中创建一个文件夹和一个文本文件.与WhatsApp相同.另外,我需要向该文件中写入一些数据.

I am trying to create a folder and a text file in that folder on the device's external storage. The same as WhatsApp does. Also, I need to write some data to that file.

是否可以以xamarin形式进行此操作?还是我们需要使用依赖项服务?

Is it possible to do this in xamarin forms? Or should we need to use a dependency service?

预先感谢

更新

@Lucas Zhang-MSFT我尝试了依赖服务,但设备上没有文件或文件夹生成.我无法使用 PCLStorage ,因为我需要在设备外部文件夹中创建文件.

@Lucas Zhang - MSFT I try your dependency service but no file or folder is generating on the device. I can't use PCLStorage since I need to create the file in device external folder.

这实际上不是我要找的.我首先需要创建一个文件夹,然后在该文件夹上创建一个文本文件.我需要在不丢失先前数据的情况下将数据写入该文件.该文件和文件夹应该在设备文件管理器上可见,因为该文件将由用户使用.

This is not actually I am looking for. I need a create a folder first, then a text file on that folder. I need to write data into that file without losing the previous data. That file and folder should be visible on the device file manager because that file is going to use by the users.

我认为该界面应具有2个功能.

I think the interface should have 2 functions.

无效CreateFolderAndFile(string folderName,string FileName); //在此功能上,我们需要在设备文件夹上创建一个文件夹和文件(如果尚不存在).如果已经存在,则什么也不做.

无效WriteDataToFile(字符串数据); //在此功能上,我们需要将数据写入顶部添加的文件中

推荐答案

这是xamarin形式的吗?还是我们需要使用依赖项服务?

do this in xamarin forms? Or should we need to use a dependency service?

选项1:

我们当然需要使用依赖服务.

Option 1:

Of course we need to use dependency service .

public async Task SaveAndView(string fileName, String contentType, MemoryStream stream)
        {
            try
            {
                string root = null;
                //Get the root path in android device.
                if (Android.OS.Environment.IsExternalStorageEmulated)
                {
                    root = Android.OS.Environment.ExternalStorageDirectory.ToString();
                }
                else
                    root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                //Create directory and file 
                Java.IO.File myDir = new Java.IO.File(root + "/meusarquivos");
                myDir.Mkdir();

                Java.IO.File file = new Java.IO.File(myDir, fileName);

                //Remove if the file exists
                if (file.Exists()) file.Delete();

                //Write the stream into the file
                FileOutputStream outs = new FileOutputStream(file);
                outs.Write(stream.ToArray());

                outs.Flush();
                outs.Close();
           }
            catch (Exception ex)
            {
                //...
            }
        }

await DependencyService.Get<ISave>().SaveAndView(xxx.ToString() + ".pdf", "application/pdf", stream);

不要忘记添加以下权限并获得运行时权限.

Do not forget to add following permission and achieve runtime permission.

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

在iOS中

iOS对应用程序对文件系统的操作施加了一些限制,以保护应用程序数据的安全性并保护用户免受恶意应用程序的侵害.这些限制是应用程序沙箱"的一部分,应用程序沙箱"是一组规则,用于限制应用程序对文件,首选项,网络资源,硬件等的访问.它无法访问其他应用程序的文件.

in iOS

iOS imposes some restrictions on what an application can do with the file system to preserve the security of an application’s data, and to protect users from malignant apps. These restrictions are part of the Application Sandbox – a set of rules that limits an application’s access to files, preferences, network resources, hardware, etc. An application is limited to reading and writing files within its home directory (installed location); it cannot access another application’s files.

您可以检查文档有关更多详细信息.

You could check the docs for more details .

如果您确实想直接在Forms中实现它.我们可以使用插件 PCLStorage 来自nuget.

If you do want to implement it in Forms directly . We could use the plugin PCLStorage from nuget .

跨平台本地文件夹

在Xamarin.Form中, PCLStorage API将使用下面给出的代码帮助我们检索所有平台的本地文件夹名称和路径.无需编写任何特定于平台的代码即可访问本地文件夹.

In Xamarin.Form, the PCLStorage API will help us to retrieve all the platforms' local folder names and paths, using the code given below. There is no need to write any platform-specific code to access the local folder.

Using PCLStorage;  

IFolder folder = FileSystem.Current.LocalStorage; 

创建新文件夹

要在本地文件夹中创建新的子文件夹,请调用CreateFolderAsync方法.

To create a new subfolder in the local folder, call the CreateFolderAsync method.

string folderName ="xxx" ;  
IFolder folder = FileSystem.Current.LocalStorage;  
folder = await folder.CreateFolderAsync(folderName, CreationCollisionOption.ReplaceExisting);  

创建新文件

要在本地文件夹中创建新文件,请调用CreateFileAsync方法.

To create a new file in the local folder, call the CreateFileAsync method.

string filename="username.txt";  
IFolder folder = FileSystem.Current.LocalStorage;  
IFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);  

检查文件夹已存在

我们可以检查特定文件夹中的现有文件夹,如下所示.

We can check for an existing folder in a particular folder, as shown below.

public async static Task<bool> IsFolderExistAsync(this string folderName, IFolder rootFolder = null)  
     {  
         // get hold of the file system  
         IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;  
         ExistenceCheckResult folderexist = await folder.CheckExistsAsync(folderName);  
         // already run at least once, don't overwrite what's there  
         if (folderexist == ExistenceCheckResult.FolderExists)  
         {  
             return true;  
  
         }  
         return false;  
     }  

检查文件已存在

我们可以检查特定文件夹中的现有文件,如下所示.

We can check for an existing file in a particular folder, as shown below.

public async static Task<bool> IsFileExistAsync(this string fileName, IFolder rootFolder = null)  
        {  
            // get hold of the file system  
            IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;  
            ExistenceCheckResult folderexist = await folder.CheckExistsAsync(fileName);  
            // already run at least once, don't overwrite what's there  
            if (folderexist == ExistenceCheckResult.FileExists)  
            {  
                return true;  
  
            }  
            return false;  
        }  

写入文件

如果要写入任何扩展文件文档,只需使用WriteAllTextAsync方法进行写入.

If you want to write any extension file document, just use the WriteAllTextAsync method for write.

public async static Task<bool> WriteTextAllAsync(this string filename, string content = "", IFolder rootFolder = null)  
      {  
          IFile file = await filename.CreateFile(rootFolder);  
          await file.WriteAllTextAsync(content);  
          return true;  
      }  

注意:您仍然需要在Android项目中添加权限.

Note: you still need to add permission in Android project .

File类提供了在共享项目中创建,删除和读取文件的相关方法,但是它只能访问应用程序文件夹.

The File class provides the related method to create, delete, and read files in the shared project, but it can only access the application folder.

File.WriteAllText(fileName, text);
string text = File.ReadAllText(fileName);

要在外部存储中创建文件,请尝试使用DependencyService在本机平台上实现该功能.

To create a file in the external storage, try to achieve the function on the native platform using DependencyService.

1.创建一个接口以定义方法

public interface IAccessFile
{
    void CreateFile(string FileName);
}

2.在android平台上实现服务

[assembly: Xamarin.Forms.Dependency(typeof(AccessFileImplement))]
namespace XamarinFirebase.Droid
{
    public class AccessFileImplement : IAccessFile
    {
        void CreateFile(string FileName)
        {
            string text = "xxx";
            byte[] data = Encoding.ASCII.GetBytes(text);
            string DownloadsPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
            string filePath = Path.Combine(DownloadsPath, FileName);
            File.WriteAllBytes(filePath, data);
        }
    }
}

3.在共享项目中使用DependencyService命令

DependencyService.Get<IAccessFile>().CreateFile("myfile.txt");

它不能在iOS平台上使用,iOS对应用程序可以使用文件系统执行哪些操作以保持应用程序数据的安全性施加了一些限制.应用程序仅限于在其主目录(安装位置)中读写文件;它无法访问其他应用程序的文件.

It cannot be available on iOS platform, iOS imposes some restrictions on what an application can do with the file system to preserve the security of an application’s data. An application is limited to reading and writing files within its home directory (installed location); it cannot access another application’s files.

相关教程:

https://docs.microsoft.com/en-us/xamarin/android/platform/files/external-storage?tabs = windows

https://docs.microsoft.com/en-us/xamarin/ios/app-fundamentals/file-system#special-considerations

这篇关于Xamarin形式:如何在设备外部存储中创建文件夹和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆